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
2,792
mitmproxy__mitmproxy-2792
[ "2765" ]
3b5237c55f4ecc30a0f9d0980965490d6e034ad1
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -365,7 +365,8 @@ def load_file(self, path: mitmproxy.types.Path) -> None: self.add([i.copy()]) except IOError as e: ctx.log.error(e.strerror) - return + except exceptions.FlowReadException as e: + ctx.log.error(str(e)) @command.command("view.go") def go(self, dst: int) -> None:
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 @@ -175,6 +175,10 @@ def test_load(tmpdir): v.load_file("nonexistent_file_path") except IOError: assert False + with open(path, "wb") as f: + f.write(b"invalidflows") + v.load_file(path) + assert tctx.master.has_log("Invalid data format.") def test_resolve():
Mitmproxy crashes, when giving it the file without flows data ##### Steps to reproduce the problem: 1. Open mitmproxy. 2. Press `Shift L` to load flows from the file. 3. Set the filepath with any data excluding flows data. For example: `/home/kajoj/myphoto.jpg` I am seeing: ``` Traceback (most recent call last): File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/io/io.py", line 43, in stream tnetstring.load(self.fo), File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/io/tnetstring.py", line 178, in load raise ValueError("not a tnetstring: missing or invalid length prefix") ValueError: not a tnetstring: missing or invalid length prefix During handling of the above exception, another exception occurred: 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 361, in load_file for i in io.FlowReader(f).stream(): File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/io/io.py", line 55, in stream raise exceptions.FlowReadException("Invalid data format.") mitmproxy.exceptions.FlowReadException: Invalid data format. ``` ##### 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-13T23:33:23
mitmproxy/mitmproxy
2,793
mitmproxy__mitmproxy-2793
[ "2399" ]
3b5237c55f4ecc30a0f9d0980965490d6e034ad1
diff --git a/mitmproxy/net/http/url.py b/mitmproxy/net/http/url.py --- a/mitmproxy/net/http/url.py +++ b/mitmproxy/net/http/url.py @@ -76,7 +76,7 @@ def encode(s: Sequence[Tuple[str, str]], similar_to: str=None) -> str: encoded = urllib.parse.urlencode(s, False, errors="surrogateescape") - if remove_trailing_equal: + if encoded and remove_trailing_equal: encoded = encoded.replace("=&", "&") if encoded[-1] == '=': encoded = encoded[:-1]
diff --git a/test/mitmproxy/net/http/test_url.py b/test/mitmproxy/net/http/test_url.py --- a/test/mitmproxy/net/http/test_url.py +++ b/test/mitmproxy/net/http/test_url.py @@ -108,6 +108,7 @@ def test_empty_key_trailing_equal_sign(): def test_encode(): assert url.encode([('foo', 'bar')]) assert url.encode([('foo', surrogates)]) + assert not url.encode([], similar_to="justatext") def test_decode():
MITM Proxy Crashes on when editing a "form" Stack trace: ``` Traceback (most recent call last): File "/Users/ograff/mitmproxy/mitmproxy/tools/console/master.py", line 202, in run self.loop.run() File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/window.py", line 274, in keypress k = fs.keypress(size, k) File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/overlay.py", line 117, in keypress key = self.master.keymap.handle("chooser", key) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/keymap.py", line 123, in handle return self.executor(b.command) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/commandeditor.py", line 24, in __call__ ret = self.master.commands.call(cmd) File "/Users/ograff/mitmproxy/mitmproxy/command.py", line 144, in call return self.call_args(parts[0], parts[1:]) File "/Users/ograff/mitmproxy/mitmproxy/command.py", line 135, in call_args return self.commands[path].call(args) File "/Users/ograff/mitmproxy/mitmproxy/command.py", line 106, in call ret = self.func(*pargs) File "/Users/ograff/mitmproxy/mitmproxy/command.py", line 197, in wrapper return function(*args, **kwargs) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/consoleaddons.py", line 125, in nav_select self.master.inject_key("m_select") File "/Users/ograff/mitmproxy/mitmproxy/tools/console/master.py", line 178, in inject_key self.loop.process_input([key]) File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/main_loop.py", line 503, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/window.py", line 274, in keypress k = fs.keypress(size, k) File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/overlay.py", line 120, in keypress signals.pop_view_state.send(self) File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/blinker/base.py", line 267, in send for receiver in self.receivers_for(sender)] File "/Users/ograff/mitmproxy/venv/lib/python3.6/site-packages/blinker/base.py", line 267, in <listcomp> for receiver in self.receivers_for(sender)] File "/Users/ograff/mitmproxy/mitmproxy/tools/console/window.py", line 207, in pop if self.focus_stack().pop(): File "/Users/ograff/mitmproxy/mitmproxy/tools/console/window.py", line 81, in pop self.call("layout_popping") File "/Users/ograff/mitmproxy/mitmproxy/tools/console/window.py", line 93, in call getattr(self.top_window(), name)(*args, **kwargs) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 463, in layout_popping self.call(self._w, "layout_popping") File "/Users/ograff/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 441, in call f(*args, **kwargs) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 313, in layout_popping self.callback(self.data_out(res), *self.cb_args, **self.cb_kwargs) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 456, in set_data_update self.set_data(vals, flow) File "/Users/ograff/mitmproxy/mitmproxy/tools/console/grideditor/editors.py", line 64, in set_data flow.request.urlencoded_form = vals File "/Users/ograff/mitmproxy/mitmproxy/net/http/request.py", line 462, in urlencoded_form self._set_urlencoded_form(value) File "/Users/ograff/mitmproxy/mitmproxy/net/http/request.py", line 444, in _set_urlencoded_form self.content = mitmproxy.net.http.url.encode(form_data, self.content.decode()).encode() File "/Users/ograff/mitmproxy/mitmproxy/net/http/url.py", line 81, in encode if encoded[-1] == '=': IndexError: string index out of range ``` mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Shutting down... ##### Steps to reproduce the problem: 1. Enter a flow 2. Press "e" 3. Select "form" ##### Any other comments? What have you tried so far? `encoded` is an empty string but probably shouldn't be. Changing `mitmproxy/net/http/url.py` to just check for an empty string and not index into it if its empty results in an empty request body after exiting the editor. ##### System information ``` Mitmproxy version: 3.0.0 (2.0.0dev0631-0x30927468) Python version: 3.6.0 Platform: Darwin-16.5.0-x86_64-i386-64bit SSL version: OpenSSL 1.1.0f 25 May 2017 Mac version: 10.12.4 ('', '', '') x86_64 ```
I have just reproduced it with `pathoc`. 1. Run Mitmproxy. 2. `pathoc -c example.com:80 localhost:8080 'post:/:b200'`. 3. Enter the corresponding flow. 4. Press `e`. 5. `Form`. The same traceback.
2018-01-14T12:28:52
mitmproxy/mitmproxy
2,796
mitmproxy__mitmproxy-2796
[ "2752" ]
6e7030fcfb31c5ba4856dcc02ba06a50f2c3ab6b
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 @@ -5,6 +5,7 @@ from mitmproxy import command from mitmproxy import exceptions from mitmproxy import flow +from mitmproxy import http from mitmproxy import contentviews from mitmproxy.utils import strutils import mitmproxy.types @@ -378,6 +379,12 @@ def edit_focus(self, part: str) -> None: # but for now it is. if not flow: raise exceptions.CommandError("No flow selected.") + require_dummy_response = ( + part in ("response-headers", "response-body", "set-cookies") and + flow.response is None + ) + if require_dummy_response: + flow.response = http.HTTPResponse.make() if part == "cookies": self.master.switch_view("edit_focus_cookies") elif part == "form": @@ -395,8 +402,6 @@ def edit_focus(self, part: str) -> None: 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
Editing set-cookies while no response is present crashes mitmproxy ##### Steps to reproduce the problem: 1. Create a new flow by pressing `n`. 2. Enter, e -> set-cookies ``` Traceback (most recent call last): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/master.py", line 216, in run self.loop.run() File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/home/user/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/home/user/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/home/user/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 "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 299, in keypress k = super().keypress(size, k) File "/home/user/venv/lib/python3.5/site-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/window.py", line 36, in keypress ret = super().keypress(size, key) File "/home/user/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/user/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/overlay.py", line 130, in keypress self.master.keymap.handle("global", key) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/keymap.py", line 130, in handle return self.executor(b.command) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/commandexecutor.py", line 17, in __call__ ret = self.master.commands.call(cmd) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 221, in call return self.call_args(parts[0], parts[1:]) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 212, in call_args return self.commands[path].call(args) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 101, in call ret = self.func(*pargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 251, in wrapper return function(*args, **kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/consoleaddons.py", line 174, in nav_select self.master.inject_key("m_select") File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/master.py", line 181, in inject_key self.loop.process_input([key]) File "/home/user/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 "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 299, in keypress k = super().keypress(size, k) File "/home/user/venv/lib/python3.5/site-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/window.py", line 36, in keypress ret = super().keypress(size, key) File "/home/user/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/user/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/overlay.py", line 120, in keypress self.callback(self.choices[self.walker.index]) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/consoleaddons.py", line 264, in callback self.master.commands.call(subcmd + " " + repl) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 221, in call return self.call_args(parts[0], parts[1:]) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 212, in call_args return self.commands[path].call(args) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 101, in call ret = self.func(*pargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 251, in wrapper return function(*args, **kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/consoleaddons.py", line 409, in edit_focus self.master.switch_view("edit_focus_setcookies") File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/master.py", line 236, in switch_view self.window.push(name) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 223, in push self.focus_changed() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 200, in focus_changed i.call("focus_changed") File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 110, in call getattr(self.top_window(), name)(*args, **kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 471, in focus_changed self.get_data(self.master.view.focus.flow), File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/grideditor/editors.py", line 149, in get_data return self.data_in(flow.response.cookies.items(multi=True)) AttributeError: 'NoneType' object has no attribute 'cookies' ``` ##### System information Mitmproxy: 3.0.0.dev0002 (commit 299df48) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-43-Microsoft-x86_64-with-Ubuntu-16.04-xenial
The same situation with `response-headers`: ``` 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 305, in keypress k = super().keypress(size, k) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 47, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 130, in keypress self.master.keymap.handle("global", key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/keymap.py", line 130, in handle return self.executor(b.command) 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/tools/console/consoleaddons.py", line 174, in nav_select self.master.inject_key("m_select") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/master.py", line 181, in inject_key self.loop.process_input([key]) 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 305, in keypress k = super().keypress(size, k) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 47, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 120, in keypress self.callback(self.choices[self.walker.index]) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/consoleaddons.py", line 264, in callback self.master.commands.call(subcmd + " " + repl) 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/tools/console/consoleaddons.py", line 392, in edit_focus self.master.switch_view("edit_focus_response_headers") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/master.py", line 236, in switch_view self.window.push(name) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 235, in push self.focus_changed() File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 212, in focus_changed i.call("focus_changed") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 121, in call getattr(self.top_window(), name)(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 471, in focus_changed self.get_data(self.master.view.focus.flow), File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/editors.py", line 48, in get_data return flow.response.headers.fields AttributeError: 'NoneType' object has no attribute 'headers' ```
2018-01-15T18:03:09
mitmproxy/mitmproxy
2,798
mitmproxy__mitmproxy-2798
[ "2786" ]
6e7030fcfb31c5ba4856dcc02ba06a50f2c3ab6b
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 @@ -55,7 +55,9 @@ def focus_changed(self): (self.tab_response, self.view_response), (self.tab_details, self.view_details), ] - self.show() + self.show() + else: + self.master.window.pop() @property def view(self):
Deleting the last flow from within the flowlist crashes mitmproxy ##### Steps to reproduce the problem: 1. `mitmproxy` 2. `n` `enter` `enter` `d` ``` Traceback (most recent call last): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/master.py", line 216, in run self.loop.run() File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run self._run() File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run self.event_loop.run() [*:8080] File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run self._loop() File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop self._watch_files[fd]() File "/home/user/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/home/user/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input callback(processed, processed_codes) File "/home/user/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update self.process_input(keys) File "/home/user/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 "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 312, in keypress k File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/keymap.py", line 130, in handle return self.executor(b.command) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/commandexecutor.py", line 17, in __call__ ret = self.master.commands.call(cmd) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 221, in call return self.call_args(parts[0], parts[1:]) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 212, in call_args return self.commands[path].call(args) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 101, in call ret = self.func(*pargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/command.py", line 251, in wrapper return function(*args, **kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/addons/view.py", line 413, in remove self.sig_view_remove.send(self, flow=f, index=idx) File "/home/user/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in send for receiver in self.receivers_for(sender)] File "/home/user/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in <listcomp> for receiver in self.receivers_for(sender)] File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/addons/view.py", line 566, in _sig_view_remove self.flow = None File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/addons/view.py", line 547, in flow self.sig_change.send(self) File "/home/user/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in send for receiver in self.receivers_for(sender)] File "/home/user/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in <listcomp> for receiver in self.receivers_for(sender)] File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 209, in focus_changed i.call("focus_changed") File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/window.py", line 118, in call getattr(self.top_window(), name)(*args, **kwargs) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/flowview.py", line 231, in focus_changed self.body.focus_changed() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/flowview.py", line 58, in focus_changed self.show() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/tabs.py", line 52, in show txt = self.tabs[i][0]() File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/tools/console/flowview.py", line 69, in tab_request if self.flow.intercepted and not self.flow.response: AttributeError: 'NoneType' object has no attribute 'intercepted' ``` ##### System information Mitmproxy: 3.0.0.dev1147 (commit b7db304) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-43-Microsoft-x86_64-with-Ubuntu-16.04-xenial
2018-01-17T21:06:49
mitmproxy/mitmproxy
2,802
mitmproxy__mitmproxy-2802
[ "2779", "2779" ]
9751f0695ded0c59097dda6768d31effdcaf0968
diff --git a/mitmproxy/addons/__init__.py b/mitmproxy/addons/__init__.py --- a/mitmproxy/addons/__init__.py +++ b/mitmproxy/addons/__init__.py @@ -20,6 +20,7 @@ from mitmproxy.addons import streambodies from mitmproxy.addons import save from mitmproxy.addons import upstream_auth +from mitmproxy.addons import share def default_addons(): @@ -46,4 +47,5 @@ def default_addons(): streambodies.StreamBodies(), save.Save(), upstream_auth.UpstreamAuth(), + share.Share() ] diff --git a/mitmproxy/addons/save.py b/mitmproxy/addons/save.py --- a/mitmproxy/addons/save.py +++ b/mitmproxy/addons/save.py @@ -61,8 +61,8 @@ def save(self, flows: typing.Sequence[flow.Flow], path: mitmproxy.types.Path) -> except IOError as v: raise exceptions.CommandError(v) from v stream = io.FlowWriter(f) - for i in flows: - stream.add(i) + for x in flows: + stream.add(x) f.close() ctx.log.alert("Saved %s flows." % len(flows)) diff --git a/mitmproxy/addons/share.py b/mitmproxy/addons/share.py new file mode 100644 --- /dev/null +++ b/mitmproxy/addons/share.py @@ -0,0 +1,79 @@ +import typing +import random +import string +import io +import http.client + +from mitmproxy import command +import mitmproxy.io +from mitmproxy import ctx +from mitmproxy import flow +from mitmproxy.net.http import status_codes + + +class Share: + def encode_multipart_formdata(self, filename: str, content: bytes) -> typing.Tuple[str, bytes]: + params = {"key": filename, "acl": "bucket-owner-full-control", "Content-Type": "application/octet-stream"} + LIMIT = b'---------------------------198495659117975628761412556003' + CRLF = b'\r\n' + l = [] + for (key, value) in params.items(): + l.append(b'--' + LIMIT) + l.append(b'Content-Disposition: form-data; name="%b"' % key.encode("utf-8")) + l.append(b'') + l.append(value.encode("utf-8")) + l.append(b'--' + LIMIT) + l.append(b'Content-Disposition: form-data; name="file"; filename="%b"' % filename.encode("utf-8")) + l.append(b'Content-Type: application/octet-stream') + l.append(b'') + l.append(content) + l.append(b'--' + LIMIT + b'--') + l.append(b'') + body = CRLF.join(l) + content_type = 'multipart/form-data; boundary=%s' % LIMIT.decode("utf-8") + return content_type, body + + def post_multipart(self, host: str, filename: str, content: bytes) -> str: + """ + Upload flows to the specified S3 server. + + Returns: + - The share URL, if upload is successful. + Raises: + - IOError, otherwise. + """ + content_type, body = self.encode_multipart_formdata(filename, content) + conn = http.client.HTTPConnection(host) # FIXME: This ultimately needs to be HTTPSConnection + headers = {'content-type': content_type} + try: + conn.request("POST", "", body, headers) + resp = conn.getresponse() + except Exception as v: + raise IOError(v) + finally: + conn.close() + if resp.status != 204: + if resp.reason: + reason = resp.reason + else: + reason = status_codes.RESPONSES.get(resp.status, str(resp.status)) + raise IOError(reason) + return "https://share.mitmproxy.org/%s" % filename + + @command.command("share.flows") + def share(self, flows: typing.Sequence[flow.Flow]) -> None: + u_id = "".join(random.choice(string.ascii_lowercase + string.digits)for _ in range(7)) + f = io.BytesIO() + stream = mitmproxy.io.FlowWriter(f) + for x in flows: + stream.add(x) + f.seek(0) + content = f.read() + try: + res = self.post_multipart('upload.share.mitmproxy.org.s3.amazonaws.com', u_id, content) + except IOError as v: + ctx.log.warn("%s" % v) + else: + ctx.log.alert("%s" % res) + finally: + f.close() \ No newline at end of file
diff --git a/test/mitmproxy/addons/test_share.py b/test/mitmproxy/addons/test_share.py new file mode 100644 --- /dev/null +++ b/test/mitmproxy/addons/test_share.py @@ -0,0 +1,34 @@ +from unittest import mock +import http.client + +from mitmproxy.test import taddons +from mitmproxy.test import tflow + +from mitmproxy.addons import share +from mitmproxy.addons import view + + +def test_share_command(): + with mock.patch('mitmproxy.addons.share.http.client.HTTPConnection') as mock_http: + sh = share.Share() + with taddons.context() as tctx: + mock_http.return_value.getresponse.return_value = mock.MagicMock(status=204, reason="No Content") + sh.share([tflow.tflow(resp=True)]) + assert tctx.master.has_log("https://share.mitmproxy.org/") + + mock_http.return_value.getresponse.return_value = mock.MagicMock(status=403, reason="Forbidden") + sh.share([tflow.tflow(resp=True)]) + assert tctx.master.has_log("Forbidden") + + mock_http.return_value.getresponse.return_value = mock.MagicMock(status=404, reason="") + sh.share([tflow.tflow(resp=True)]) + assert tctx.master.has_log("Not Found") + + mock_http.return_value.request.side_effect = http.client.CannotSendRequest("Error in sending req") + sh.share([tflow.tflow(resp=True)]) + assert tctx.master.has_log("Error in sending req") + + v = view.View() + tctx.master.addons.add(v) + tctx.master.addons.add(sh) + tctx.master.commands.call_args("share.flows", ["@shown"])
Implement `share` command @MatthewShao implemented a really cool static viewer based on mitmweb last summer: http://honeynet.org/node/1359. Long story short, one can upload a mitmproxy flow file at share.mitmproxy.org and will get a shareable link in return. 😃 To make this more accessible, I think it would be awesome to have a mitmproxy command that takes a bunch of flows as argument, uploads them directly from within mitmproxy, and returns a URL to share. Implement `share` command @MatthewShao implemented a really cool static viewer based on mitmweb last summer: http://honeynet.org/node/1359. Long story short, one can upload a mitmproxy flow file at share.mitmproxy.org and will get a shareable link in return. 😃 To make this more accessible, I think it would be awesome to have a mitmproxy command that takes a bunch of flows as argument, uploads them directly from within mitmproxy, and returns a URL to share.
For some related code, see e.g. the save command: https://github.com/mitmproxy/mitmproxy/blob/67300fab3119f055a6cbb43b7cbc9d33e849d165/mitmproxy/addons/save.py#L53-L67 It would be nice to use HTTP upload functionality from Python's stdlib opposed to requests to keep our library footprint small. @mhils Just want to clarify. I press, for example, `u` button, mitmproxy takes all available flows, uploads them at _share.mitmproxy.org_ and then gets _url_, displaying it in Status Bar. But how will we be able to copy it and use somewhere? I've been thinking about this as well. It's a very exciting direction. This is certainly a 4.0 or beyond feature - we have quite a bit of work/thinking to do about the server component here. @kajojify: For now, let's just add a command that can be manually invoked (press `:` and then enter the command and a flowspec) and logs the URL. Hi, I would like to work on it :) Will keep you updated as I progress I am almost done, one doubt I have is that since the data is being encoded by multipart/form-data , I need to load the file into the memory first, can I use 'poster' to achieve this or go forward with standard libraries? @mhils ![mitm-upload half](https://user-images.githubusercontent.com/19341613/35057494-20107d5a-fbdb-11e7-8295-b7a2216dc9df.png) Hi, stdlib please. As in your screenshot, we should accept a FlowSpec, i.e. the command will be given a list of flows, which it can then serialize in memory to a BytesIO instance (see [mitmproxy.io](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/io.py)), which we then can upload. :) We want filesizes to be reasonable anyway, so in-memory is not an issue here. Hi, So the approach I am using is that I am saving the flows in a temporary file, (the name will be the unique 7 letter id), the doubt I have is that to send a POST request I need to read the contents of the file so should I use `read_flows_from_paths(paths)` or ``` path = os.path.expanduser(path) with open(path, "rb") as f: content = f.read() ``` and use `content` to send the POST request? For some related code, see e.g. the save command: https://github.com/mitmproxy/mitmproxy/blob/67300fab3119f055a6cbb43b7cbc9d33e849d165/mitmproxy/addons/save.py#L53-L67 It would be nice to use HTTP upload functionality from Python's stdlib opposed to requests to keep our library footprint small. @mhils Just want to clarify. I press, for example, `u` button, mitmproxy takes all available flows, uploads them at _share.mitmproxy.org_ and then gets _url_, displaying it in Status Bar. But how will we be able to copy it and use somewhere? I've been thinking about this as well. It's a very exciting direction. This is certainly a 4.0 or beyond feature - we have quite a bit of work/thinking to do about the server component here. @kajojify: For now, let's just add a command that can be manually invoked (press `:` and then enter the command and a flowspec) and logs the URL. Hi, I would like to work on it :) Will keep you updated as I progress I am almost done, one doubt I have is that since the data is being encoded by multipart/form-data , I need to load the file into the memory first, can I use 'poster' to achieve this or go forward with standard libraries? @mhils ![mitm-upload half](https://user-images.githubusercontent.com/19341613/35057494-20107d5a-fbdb-11e7-8295-b7a2216dc9df.png) Hi, stdlib please. As in your screenshot, we should accept a FlowSpec, i.e. the command will be given a list of flows, which it can then serialize in memory to a BytesIO instance (see [mitmproxy.io](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/io.py)), which we then can upload. :) We want filesizes to be reasonable anyway, so in-memory is not an issue here. Hi, So the approach I am using is that I am saving the flows in a temporary file, (the name will be the unique 7 letter id), the doubt I have is that to send a POST request I need to read the contents of the file so should I use `read_flows_from_paths(paths)` or ``` path = os.path.expanduser(path) with open(path, "rb") as f: content = f.read() ``` and use `content` to send the POST request?
2018-01-18T20:46:01
mitmproxy/mitmproxy
2,803
mitmproxy__mitmproxy-2803
[ "2777", "2777" ]
6dd336fcec6dc32c4986b6c20189bf1b2132153c
diff --git a/mitmproxy/tools/console/commander/commander.py b/mitmproxy/tools/console/commander/commander.py --- a/mitmproxy/tools/console/commander/commander.py +++ b/mitmproxy/tools/console/commander/commander.py @@ -47,7 +47,7 @@ def cycle(self) -> str: ) -class CommandBuffer(): +class CommandBuffer: def __init__(self, master: mitmproxy.master.Master, start: str = "") -> None: self.master = master self.text = self.flatten(start) 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 @@ -277,6 +277,17 @@ def console_command(self, *partial: str) -> None: """ signals.status_prompt_command.send(partial=" ".join(partial)) # type: ignore + @command.command("console.command.set") + def console_command_set(self, option: str) -> None: + """ + Prompt the user to set an option of the form "key[=value]". + """ + option_value = getattr(self.master.options, option, None) + current_value = option_value if option_value else "" + self.master.commands.call( + "console.command set %s=%s" % (option, current_value) + ) + @command.command("console.view.keybindings") def view_keybindings(self) -> None: """View the commands list.""" 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 @@ -26,8 +26,8 @@ def map(km): km.add("ctrl b", "console.nav.pageup", ["global"], "Page up") km.add("I", "console.intercept.toggle", ["global"], "Toggle intercept") - km.add("i", "console.command set intercept=", ["global"], "Set intercept") - km.add("W", "console.command set save_stream_file=", ["global"], "Stream to file") + km.add("i", "console.command.set intercept", ["global"], "Set intercept") + km.add("W", "console.command.set save_stream_file", ["global"], "Stream to file") km.add("A", "flow.resume @all", ["flowlist", "flowview"], "Resume all intercepted flows") km.add("a", "flow.resume @focus", ["flowlist", "flowview"], "Resume this intercepted flow") km.add( @@ -46,7 +46,7 @@ def map(km): ["flowlist", "flowview"], "Export this flow to file" ) - km.add("f", "console.command set view_filter=", ["flowlist"], "Set view filter") + km.add("f", "console.command.set view_filter", ["flowlist"], "Set view filter") km.add("F", "set console_focus_follow=toggle", ["flowlist"], "Set focus follow") km.add( "ctrl l",
Flow filters don't persist between invocations of `f` ##### Steps to reproduce the problem: 1 - Hit `f` type in filter, make a typo 2 - Hit 'f' again to fix the typo ##### Expected behaviour On second hit of f, when filter in use already the command line shows the current filter. ##### Current behaviour On second hit of f, whn filter in use already, the filter is cleared. ##### System information Mitmproxy 3 RC2 Flow filters don't persist between invocations of `f` ##### Steps to reproduce the problem: 1 - Hit `f` type in filter, make a typo 2 - Hit 'f' again to fix the typo ##### Expected behaviour On second hit of f, when filter in use already the command line shows the current filter. ##### Current behaviour On second hit of f, whn filter in use already, the filter is cleared. ##### System information Mitmproxy 3 RC2
Thanks again - this is very useful UX feedback! Also haven't found a way to copy response body to clipboard. Well no easy way, with a single key, I think it's doable with the new command interface. I'll make a new report if I remember. On Tue, Jan 9, 2018 at 5:41 PM Maximilian Hils <[email protected]> wrote: > Thanks again - this is very useful UX feedback! > > — > You are receiving this because you authored the thread. > Reply to this email directly, view it on GitHub > <https://github.com/mitmproxy/mitmproxy/issues/2777#issuecomment-356438280>, > or mute the thread > <https://github.com/notifications/unsubscribe-auth/AAg7PBeFkdn9xlcu1QFZ4427bgntlo3Jks5tI-srgaJpZM4RYgDK> > . > Thanks again - this is very useful UX feedback! Also haven't found a way to copy response body to clipboard. Well no easy way, with a single key, I think it's doable with the new command interface. I'll make a new report if I remember. On Tue, Jan 9, 2018 at 5:41 PM Maximilian Hils <[email protected]> wrote: > Thanks again - this is very useful UX feedback! > > — > You are receiving this because you authored the thread. > Reply to this email directly, view it on GitHub > <https://github.com/mitmproxy/mitmproxy/issues/2777#issuecomment-356438280>, > or mute the thread > <https://github.com/notifications/unsubscribe-auth/AAg7PBeFkdn9xlcu1QFZ4427bgntlo3Jks5tI-srgaJpZM4RYgDK> > . >
2018-01-19T00:19:20
mitmproxy/mitmproxy
2,808
mitmproxy__mitmproxy-2808
[ "2800" ]
6dd336fcec6dc32c4986b6c20189bf1b2132153c
diff --git a/mitmproxy/contentviews/base.py b/mitmproxy/contentviews/base.py --- a/mitmproxy/contentviews/base.py +++ b/mitmproxy/contentviews/base.py @@ -49,8 +49,9 @@ def format_dict( ] entries, where key is padded to a uniform width. """ - max_key_len = max(len(k) for k in d.keys()) - max_key_len = min(max_key_len, KEY_MAX) + + max_key_len = max((len(k) for k in d.keys()), default=0) + max_key_len = min((max_key_len, KEY_MAX), default=0) for key, value in d.items(): if isinstance(key, bytes): key += b":"
diff --git a/test/mitmproxy/contentviews/test_base.py b/test/mitmproxy/contentviews/test_base.py --- a/test/mitmproxy/contentviews/test_base.py +++ b/test/mitmproxy/contentviews/test_base.py @@ -1 +1,17 @@ -# TODO: write tests +import pytest +from mitmproxy.contentviews import base + + +def test_format_dict(): + d = {"one": "two", "three": "four"} + f_d = base.format_dict(d) + assert next(f_d) + + d = {"adsfa": ""} + f_d = base.format_dict(d) + assert next(f_d) + + d = {} + f_d = base.format_dict(d) + with pytest.raises(StopIteration): + next(f_d)
Mitmproxy crashes, when viewing response body in url-encoded mode ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. `n` -> `Enter` -> `Enter` -> `m` -> `url-encoded` _I am seeing:_ ``` 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 308, in keypress k = super().keypress(size, k) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 44, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 130, in keypress self.master.keymap.handle("global", key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/keymap.py", line 130, in handle return self.executor(b.command) 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/tools/console/consoleaddons.py", line 174, in nav_select self.master.inject_key("m_select") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/master.py", line 181, in inject_key self.loop.process_input([key]) 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 308, in keypress k = super().keypress(size, k) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 44, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 121, in keypress signals.pop_view_state.send(self) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in send for receiver in self.receivers_for(sender)] File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in <listcomp> for receiver in self.receivers_for(sender)] File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 244, in pop self.focus_changed() File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 209, in focus_changed i.call("focus_changed") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 118, in call getattr(self.top_window(), name)(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/flowview.py", line 233, in focus_changed self.body.focus_changed() File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/flowview.py", line 58, in focus_changed self.show() File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/tabs.py", line 73, in show body = self.tabs[self.tab_offset][1](), File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/flowview.py", line 86, in view_request return self.conn_text(self.flow.request) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/flowview.py", line 185, in conn_text msg, body = self.content_view(viewmode, conn) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/flowview.py", line 112, in content_view return self._get_content_view(viewmode, limit, flow_modify_cache_invalidation) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/flowview.py", line 132, in _get_content_view for line in lines: File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/contentviews/__init__.py", line 85, in safe_to_print for line in lines: File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/contentviews/base.py", line 52, in format_dict max_key_len = max(len(k) for k in d.keys()) ValueError: max() arg is an empty sequence ``` ##### Any other comments? What have you tried so far? This issue is reproducible not only for request/response without body, but for `query` (maybe some others) content type as well. I continue digging. ##### System information Mitmproxy: 3.0.0.dev53 (commit 3b5237c) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-109-generic-x86_64-with-Ubuntu-16.04-xenial
2018-01-20T14:17:53
mitmproxy/mitmproxy
2,833
mitmproxy__mitmproxy-2833
[ "2824" ]
02d2ef75060784b1eec9db81e62edf4b058f86fa
diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py --- a/mitmproxy/addons/script.py +++ b/mitmproxy/addons/script.py @@ -44,13 +44,15 @@ class Script: def __init__(self, path): self.name = "scriptmanager:" + path self.path = path - self.fullpath = os.path.expanduser(path) + self.fullpath = os.path.expanduser( + path.strip("'\" ") + ) self.ns = None self.last_load = 0 self.last_mtime = 0 if not os.path.isfile(self.fullpath): - raise exceptions.OptionsError("No such script: %s" % path) + raise exceptions.OptionsError('No such script: "%s"' % self.fullpath) @property def addons(self):
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 @@ -68,6 +68,18 @@ def test_notfound(self): with pytest.raises(exceptions.OptionsError): script.Script("nonexistent") + def test_quotes_around_filename(self): + """ + Test that a script specified as '"foo.py"' works to support the calling convention of + mitmproxy 2.0, as e.g. used by Cuckoo Sandbox. + """ + path = tutils.test_data.path("mitmproxy/data/addonscripts/recorder/recorder.py") + + s = script.Script( + '"{}"'.format(path) + ) + assert '"' not in s.fullpath + def test_simple(self): with taddons.context() as tctx: sc = script.Script(
[Configuration file] keys are not used ##### Steps to reproduce the problem: 1. Create a configuration file at .mitmproxy/config.yaml 2. Set this configuration: mode: "transparent" showhost: true 3. Start mitmproxy using this command : "mitmproxy --conf config.yaml" (I'm on the .mitmproxy folder of course) The process is started but the traffic is not working 4. Start mitmproxy using this command : "mitmproxy -T --host" The process is started and the traffic is working ##### Any other comments? What have you tried so far? I tried to use the ":" and "=" as separator for the YAML file but only the ":" is recognized apparently ##### System information I have the last release of mitmproxy (v2.0.2) Well I've just notice that there is a v3 release, maybe this could help me ? I prefer to create this ticket if someone else has the same issue :)
Thanks. ``` λ echo "showhost: true" > conf.yaml λ mitmproxy --conf conf.yaml ``` work for me fine on master. Please check if 3.0 works for you. Hello ! It works now using the last release. However, it seems that I have another issue using the v3 release. I'm using cuckoo with mitmproxy for analyzing malwares/urls. I have a script in /opt/cuckoo/stuff/mitm.py that is used by the mitmdump command. When I used the v2.0.2 release of mitmproxy with cuckoo 2.0.5, it works (well, it's not working with the config.yaml file but with the v3 as I said it's ok) When I used the v3 release of mitmproxy with cuckoo 2.0.5 (same version), it doesn't work and I have an error in the mitm.err file (providing by cuckoo) saying that the script doesn't exist on the given path (while it's working using the v2 release...) Did you have any idea about this ? Cuckoo is using mitmproxy using this command : https://github.com/cuckoosandbox/cuckoo/blob/6fb0b0fd17ebd0a08424166287aca88fee53c117/cuckoo/auxiliary/mitm.py (line 57). Some screeshots : Here is my script : ![capture du 2018-01-31 11-36-39](https://user-images.githubusercontent.com/10530375/35618556-a3adca64-067b-11e8-9db7-fa30fafe55a5.png) Using v2 release : ![capture du 2018-01-31 11-36-45](https://user-images.githubusercontent.com/10530375/35618557-a3d3f5d6-067b-11e8-9713-3dfb6ad58aa9.png) Using v3 release : ![capture du 2018-01-31 11-36-56](https://user-images.githubusercontent.com/10530375/35618558-a408a376-067b-11e8-95db-0ab9f8288cdd.png) Hm, weird. It errors here: https://github.com/mitmproxy/mitmproxy/blob/aa8969b240310f265640c92e14a4b7d6363e464b/mitmproxy/addons/script.py#L52-L53. Is your `mitm.py` symlinked or is there something else that could make `isfile` fail? Yes, I have a symlink ..., but it's the same for v2 and v3 release (I change the mitmdump program in /usr/bin/) ![capture du 2018-01-31 12-06-51](https://user-images.githubusercontent.com/10530375/35619815-7d4eb7f8-067f-11e8-9d56-67884cadb5f8.png) Cuckoo is using /usr/local/bin/mitmdump, but I can try to change it What's `os.path.isfile("/opt/cuckoo/stuff/mitm.py")` for you? With this code : ![capture du 2018-01-31 13-10-09](https://user-images.githubusercontent.com/10530375/35622526-6b594ab4-0688-11e8-8659-80d596db6eba.png) As espected : ![capture du 2018-01-31 13-10-12](https://user-images.githubusercontent.com/10530375/35622528-6b87abd4-0688-11e8-8655-5dcb1e06cd3d.png) No idea why it's not working then, sorry. This is the only place where we raise this exception. I will try to find the reason. As you said, it weird to have this issue because it's only happening when the file doesn't exist and the v2 is proving that the file exists. I will keep you in touch I’ll try something tomorrow but I would like to notice you on my idea. As you can see on the code, the error is returning the path and not the fullpath variable ....... Maybe there is something wrong with the processing of path into the fullpath ? Because yes the path seems correct but what about the fullpath variable that is indeed tested ? I’ll keep you in touch I was thinking about that as well, but ```python os.path.expanduser("/opt/cuckoo/stuff/mitm.py") == "/opt/cuckoo/stuff/mitm.py" ``` should always hold true. Let me know if you find something! I think I found out what's going on : `2018-02-01 09:17:12,033 [cuckoo.auxiliary.mitm] INFO: ['/usr/local/bin/mitmdump', '-q', '-s', '"/opt/cuckoo/stuff/mitm.py" ', '-p', '8080', '-w', '/opt/cuckoo/storage/analyses/2/dump.mitm']` Here is the parameters given to mitmproxy. You will see that the script parameter contains a space at the end of the string (maybe waiting for arguments depending on the script). I think that this is the bug here ! What I don't understand is why the same parameter passed in v2 and v3 releases of mitmproxy doesn't have the same behavior when it's seems to have no modification in the code for this part.
2018-02-01T08:31:28
mitmproxy/mitmproxy
2,836
mitmproxy__mitmproxy-2836
[ "2816" ]
957a630bb5d2fcd6a8ad7092863d19e38307f090
diff --git a/mitmproxy/addons/cut.py b/mitmproxy/addons/cut.py --- a/mitmproxy/addons/cut.py +++ b/mitmproxy/addons/cut.py @@ -139,4 +139,7 @@ def clip( [strutils.always_str(v) or "" for v in vals] # type: ignore ) ctx.log.alert("Clipped %s cuts as CSV." % len(cuts)) - pyperclip.copy(fp.getvalue()) + try: + pyperclip.copy(fp.getvalue()) + except pyperclip.PyperclipException as e: + ctx.log.error(str(e)) diff --git a/mitmproxy/addons/export.py b/mitmproxy/addons/export.py --- a/mitmproxy/addons/export.py +++ b/mitmproxy/addons/export.py @@ -77,4 +77,7 @@ def clip(self, fmt: str, f: flow.Flow) -> None: raise exceptions.CommandError("No such export format: %s" % fmt) func = formats[fmt] # type: typing.Any v = strutils.always_str(func(f)) - pyperclip.copy(v) + try: + pyperclip.copy(v) + except pyperclip.PyperclipException as e: + ctx.log.error(str(e))
diff --git a/test/mitmproxy/addons/test_cut.py b/test/mitmproxy/addons/test_cut.py --- a/test/mitmproxy/addons/test_cut.py +++ b/test/mitmproxy/addons/test_cut.py @@ -7,6 +7,7 @@ from mitmproxy.test import tflow from mitmproxy.test import tutils import pytest +import pyperclip from unittest import mock @@ -89,6 +90,13 @@ def test_cut_clip(): tctx.command(c.clip, "@all", "request.method,request.content") assert pc.called + with mock.patch('pyperclip.copy') as pc: + log_message = "Pyperclip could not find a " \ + "copy/paste mechanism for your system." + pc.side_effect = pyperclip.PyperclipException(log_message) + tctx.command(c.clip, "@all", "request.method") + assert tctx.master.has_log(log_message, level="error") + def test_cut_save(tmpdir): f = str(tmpdir.join("path")) 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 @@ -1,6 +1,8 @@ -import pytest import os +import pytest +import pyperclip + from mitmproxy import exceptions from mitmproxy.addons import export # heh from mitmproxy.test import tflow @@ -111,7 +113,7 @@ def test_export_open(exception, log_message, tmpdir): def test_clip(tmpdir): e = export.Export() - with taddons.context(): + with taddons.context() as tctx: with pytest.raises(exceptions.CommandError): e.clip("nonexistent", tflow.tflow(resp=True)) @@ -122,3 +124,10 @@ def test_clip(tmpdir): with mock.patch('pyperclip.copy') as pc: e.clip("curl", tflow.tflow(resp=True)) assert pc.called + + with mock.patch('pyperclip.copy') as pc: + log_message = "Pyperclip could not find a " \ + "copy/paste mechanism for your system." + pc.side_effect = pyperclip.PyperclipException(log_message) + e.clip("raw", tflow.tflow(resp=True)) + assert tctx.master.has_log(log_message, level="error")
Mitmproxy crashes, when trying to send cuts to the clipboard without copy/paste mechanism for system ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `Ctrl l` 3. Input `: cut.clip 1 2 `. Press `Enter`. Traceback: ``` 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 309, 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_edit_text()) 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 "/usr/lib/python3.5/contextlib.py", line 77, in __exit__ self.gen.throw(type, value, traceback) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/master.py", line 68, in handlecontext yield 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/cut.py", line 139, in clip pyperclip.copy(fp.getvalue()) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/pyperclip/__init__.py", line 574, in lazy_load_stub_copy return copy(text) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/pyperclip/__init__.py", line 284, in __call__ raise PyperclipException(EXCEPT_MSG) pyperclip.PyperclipException: Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error ``` ##### Any other comments? What have you tried so far? As traceback says, the issue is relevant for Linux without installed copy/paste mechanism and can be fixed using this https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error. I think we must just handle it properly. ##### System information Mitmproxy: 3.0.0.dev64 (commit 6dd336f) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial
2018-02-03T11:18:54
mitmproxy/mitmproxy
2,847
mitmproxy__mitmproxy-2847
[ "2827", "2827" ]
05ae3460c018bc33999534ac2dbab8fa3a6c9c96
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 @@ -114,11 +114,10 @@ def _read_cookie_pairs(s, off=0): lhs, off = _read_key(s, off) lhs = lhs.lstrip() - if lhs: - rhs = None - if off < len(s) and s[off] == "=": - rhs, off = _read_value(s, off + 1, ";") - + rhs = "" + if off < len(s) and s[off] == "=": + rhs, off = _read_value(s, off + 1, ";") + if rhs or lhs: pairs.append([lhs, rhs]) off += 1 @@ -143,25 +142,24 @@ def _read_set_cookie_pairs(s: str, off=0) -> Tuple[List[TPairs], int]: lhs, off = _read_key(s, off, ";=,") lhs = lhs.lstrip() - if lhs: - rhs = None - if off < len(s) and s[off] == "=": - rhs, off = _read_value(s, off + 1, ";,") - - # Special handliing of attributes - if lhs.lower() == "expires": - # 'expires' values can contain commas in them so they need to - # be handled separately. + rhs = "" + if off < len(s) and s[off] == "=": + rhs, off = _read_value(s, off + 1, ";,") - # We actually bank on the fact that the expires value WILL - # contain a comma. Things will fail, if they don't. + # Special handling of attributes + if lhs.lower() == "expires": + # 'expires' values can contain commas in them so they need to + # be handled separately. - # '3' is just a heuristic we use to determine whether we've - # only read a part of the expires value and we should read more. - if len(rhs) <= 3: - trail, off = _read_value(s, off + 1, ";,") - rhs = rhs + "," + trail + # We actually bank on the fact that the expires value WILL + # contain a comma. Things will fail, if they don't. + # '3' is just a heuristic we use to determine whether we've + # only read a part of the expires value and we should read more. + if len(rhs) <= 3: + trail, off = _read_value(s, off + 1, ";,") + rhs = rhs + "," + trail + if rhs or lhs: pairs.append([lhs, rhs]) # comma marks the beginning of a new cookie @@ -196,13 +194,10 @@ def _format_pairs(pairs, specials=(), sep="; "): """ vals = [] for k, v in pairs: - if v is None: - vals.append(k) - else: - if k.lower() not in specials and _has_special(v): - v = ESCAPE.sub(r"\\\1", v) - v = '"%s"' % v - vals.append("%s=%s" % (k, v)) + if k.lower() not in specials and _has_special(v): + v = ESCAPE.sub(r"\\\1", v) + v = '"%s"' % v + vals.append("%s=%s" % (k, v)) return sep.join(vals)
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 @@ -6,6 +6,10 @@ cookie_pairs = [ + [ + "=uno", + [["", "uno"]] + ], [ "", [] @@ -16,7 +20,7 @@ ], [ "one", - [["one", None]] + [["one", ""]] ], [ "one=uno; two=due", @@ -36,7 +40,7 @@ ], [ "one=uno; two; three=tre", - [["one", "uno"], ["two", None], ["three", "tre"]] + [["one", "uno"], ["two", ""], ["three", "tre"]] ], [ "_lvs2=zHai1+Hq+Tc2vmc2r4GAbdOI5Jopg3EwsdUT9g=; " @@ -78,9 +82,13 @@ def test_read_quoted_string(): def test_read_cookie_pairs(): vals = [ + [ + "=uno", + [["", "uno"]] + ], [ "one", - [["one", None]] + [["one", ""]] ], [ "one=two", @@ -100,7 +108,7 @@ def test_read_cookie_pairs(): ], [ 'one="two"; three=four; five', - [["one", "two"], ["three", "four"], ["five", None]] + [["one", "two"], ["three", "four"], ["five", ""]] ], [ 'one="\\"two"; three=four', @@ -134,6 +142,12 @@ def test_cookie_roundtrips(): def test_parse_set_cookie_pairs(): pairs = [ + [ + "=uno", + [[ + ["", "uno"] + ]] + ], [ "one=uno", [[ @@ -150,7 +164,7 @@ def test_parse_set_cookie_pairs(): "one=uno; foo", [[ ["one", "uno"], - ["foo", None] + ["foo", ""] ]] ], [ @@ -199,6 +213,12 @@ def set_cookie_equal(obs, exp): [ ";", [] ], + [ + "=uno", + [ + ("", "uno", ()) + ] + ], [ "one=uno", [ diff --git a/test/mitmproxy/net/http/test_response.py b/test/mitmproxy/net/http/test_response.py --- a/test/mitmproxy/net/http/test_response.py +++ b/test/mitmproxy/net/http/test_response.py @@ -113,7 +113,7 @@ def test_get_cookies_with_parameters(self): assert attrs["domain"] == "example.com" assert attrs["expires"] == "Wed Oct 21 16:29:41 2015" assert attrs["path"] == "/" - assert attrs["httponly"] is None + assert attrs["httponly"] == "" def test_get_cookies_no_value(self): resp = tresp()
Mitmproxy crashes, when setting only value in cookies/set-cookies grideditor ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `n` -> `enter` -> `enter` -> `e` -> `cookies` (or `set-cookies`) 3. You are in grideditor. Press `a`. Choose `Value` column and add any value. You will see something like: ![image](https://user-images.githubusercontent.com/20267977/35590192-be00b434-060e-11e8-8ebd-e5bb20952aef.png) 4. Press `q` -> `e` -> `cookies` (or `set-cookies` if you're doing that for it) Traceback: ``` 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 710, in _loop self._entering_idle() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 671, in _entering_idle callback() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 564, in entering_idle self.draw_screen() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 578, in draw_screen canvas = self._topmost_widget.render(self.screen_size, focus=True) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/decoration.py", line 225, in render canv = self._original_widget.render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 455, in render (maxcol, maxrow), focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 337, in calculate_visible self._set_focus_complete( (maxcol, maxrow), focus ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 702, in _set_focus_complete (maxcol,maxrow), focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 672, in _set_focus_first_selectable (maxcol, maxrow), focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 340, in calculate_visible focus_widget, focus_pos = self.body.get_focus() File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 227, in get_focus self.lst[self.focus] File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 83, in __init__ w = self.editor.columns[i].Display(v) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/col_text.py", line 18, in Display return TDisplay(data, self.encoding_args) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/col_text.py", line 31, in __init__ super().__init__(data.encode(*self.encoding_args)) AttributeError: 'NoneType' object has no attribute 'encode' ``` You can also reproduce it for `set-cookies attributes`. Just add value without name into `set-cookies attributes`. Press `q` -> `q` to get into `flowview` tab. Press `e` -> `set-cookies`. You will see the same traceback. ##### Any other comments? What have you tried so far? This issue is relevant for 2.0.x as well. ##### System information Mitmproxy: 3.0.0.dev75 (commit 02d2ef7) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial Mitmproxy crashes, when setting only value in cookies/set-cookies grideditor ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `n` -> `enter` -> `enter` -> `e` -> `cookies` (or `set-cookies`) 3. You are in grideditor. Press `a`. Choose `Value` column and add any value. You will see something like: ![image](https://user-images.githubusercontent.com/20267977/35590192-be00b434-060e-11e8-8ebd-e5bb20952aef.png) 4. Press `q` -> `e` -> `cookies` (or `set-cookies` if you're doing that for it) Traceback: ``` 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 710, in _loop self._entering_idle() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 671, in _entering_idle callback() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 564, in entering_idle self.draw_screen() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 578, in draw_screen canvas = self._topmost_widget.render(self.screen_size, focus=True) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/decoration.py", line 225, in render canv = self._original_widget.render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 455, in render (maxcol, maxrow), focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 337, in calculate_visible self._set_focus_complete( (maxcol, maxrow), focus ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 702, in _set_focus_complete (maxcol,maxrow), focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 672, in _set_focus_first_selectable (maxcol, maxrow), focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 340, in calculate_visible focus_widget, focus_pos = self.body.get_focus() File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 227, in get_focus self.lst[self.focus] File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 83, in __init__ w = self.editor.columns[i].Display(v) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/col_text.py", line 18, in Display return TDisplay(data, self.encoding_args) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/col_text.py", line 31, in __init__ super().__init__(data.encode(*self.encoding_args)) AttributeError: 'NoneType' object has no attribute 'encode' ``` You can also reproduce it for `set-cookies attributes`. Just add value without name into `set-cookies attributes`. Press `q` -> `q` to get into `flowview` tab. Press `e` -> `set-cookies`. You will see the same traceback. ##### Any other comments? What have you tried so far? This issue is relevant for 2.0.x as well. ##### System information Mitmproxy: 3.0.0.dev75 (commit 02d2ef7) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial
@kajojify Hi, are you working on this? :) @kira0204 hi! I am not working on it. Take it, if you want :) Update: the root cause of this is because the list that is maintaining cookies is initially like `['','value']` but is getting updated to `['value',None]`, I still don't know what is causing this but will revert soon. @kajojify Hi, are you working on this? :) @kira0204 hi! I am not working on it. Take it, if you want :) Update: the root cause of this is because the list that is maintaining cookies is initially like `['','value']` but is getting updated to `['value',None]`, I still don't know what is causing this but will revert soon.
2018-02-06T23:16:07
mitmproxy/mitmproxy
2,868
mitmproxy__mitmproxy-2868
[ "2794", "2794" ]
baf4b5dc03c3b87fbef6e5df422eb7654594978f
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 @@ -429,10 +429,7 @@ def constrain_encoding(self): 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.decode())) - except ValueError: - pass + return tuple(mitmproxy.net.http.url.decode(self.get_text(strict=False))) return () def _set_urlencoded_form(self, form_data): @@ -441,7 +438,7 @@ def _set_urlencoded_form(self, form_data): This will overwrite the existing content if there is one. """ self.headers["content-type"] = "application/x-www-form-urlencoded" - self.content = mitmproxy.net.http.url.encode(form_data, self.content.decode()).encode() + self.content = mitmproxy.net.http.url.encode(form_data, self.get_text(strict=False)).encode() @property def urlencoded_form(self):
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 @@ -351,10 +351,10 @@ def test_get_urlencoded_form(self): request.headers["Content-Type"] = "application/x-www-form-urlencoded" assert list(request.urlencoded_form.items()) == [("foobar", "baz")] request.raw_content = b"\xFF" - assert len(request.urlencoded_form) == 0 + assert len(request.urlencoded_form) == 1 def test_set_urlencoded_form(self): - request = treq() + request = treq(content=b"\xec\xed") request.urlencoded_form = [('foo', 'bar'), ('rab', 'oof')] assert request.headers["Content-Type"] == "application/x-www-form-urlencoded" assert request.content
Mitmproxy with received random data crashes, when trying to edit a form ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. `pathoc -c example.com:80 localhost:8080 'post:/:b@200'` 3. Choose the corresponding flow. 4. Press `e`. 5. Form. **Traceback:** ``` 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 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 36, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 130, in keypress self.master.keymap.handle("global", key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/keymap.py", line 130, in handle return self.executor(b.command) 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/tools/console/consoleaddons.py", line 174, in nav_select self.master.inject_key("m_select") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/master.py", line 181, in inject_key self.loop.process_input([key]) 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 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 36, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 121, in keypress signals.pop_view_state.send(self) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in send for receiver in self.receivers_for(sender)] File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in <listcomp> for receiver in self.receivers_for(sender)] File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 230, in pop if self.focus_stack().pop(): File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 98, in pop self.call("layout_popping") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 110, in call getattr(self.top_window(), name)(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 463, in layout_popping self.call(self._w, "layout_popping") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 441, in call f(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 313, in layout_popping self.callback(self.data_out(res), *self.cb_args, **self.cb_kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 456, in set_data_update self.set_data(vals, flow) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/editors.py", line 65, in set_data flow.request.urlencoded_form = vals File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/net/http/request.py", line 462, in urlencoded_form self._set_urlencoded_form(value) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/net/http/request.py", line 444, in _set_urlencoded_form self.content = mitmproxy.net.http.url.encode(form_data, self.content.decode()).encode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position 0: invalid start byte ``` ##### System information Mitmproxy: 3.0.0.dev0004 (commit 68c32d8) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-109-generic-x86_64-with-Ubuntu-16.04-xenial Mitmproxy with received random data crashes, when trying to edit a form ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. `pathoc -c example.com:80 localhost:8080 'post:/:b@200'` 3. Choose the corresponding flow. 4. Press `e`. 5. Form. **Traceback:** ``` 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 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 36, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 130, in keypress self.master.keymap.handle("global", key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/keymap.py", line 130, in handle return self.executor(b.command) 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/tools/console/consoleaddons.py", line 174, in nav_select self.master.inject_key("m_select") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/master.py", line 181, in inject_key self.loop.process_input([key]) 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 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 36, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1128, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 592, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/overlay.py", line 121, in keypress signals.pop_view_state.send(self) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in send for receiver in self.receivers_for(sender)] File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/blinker/base.py", line 267, in <listcomp> for receiver in self.receivers_for(sender)] File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 230, in pop if self.focus_stack().pop(): File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 98, in pop self.call("layout_popping") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 110, in call getattr(self.top_window(), name)(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 463, in layout_popping self.call(self._w, "layout_popping") File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 441, in call f(*args, **kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 313, in layout_popping self.callback(self.data_out(res), *self.cb_args, **self.cb_kwargs) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 456, in set_data_update self.set_data(vals, flow) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/editors.py", line 65, in set_data flow.request.urlencoded_form = vals File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/net/http/request.py", line 462, in urlencoded_form self._set_urlencoded_form(value) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/net/http/request.py", line 444, in _set_urlencoded_form self.content = mitmproxy.net.http.url.encode(form_data, self.content.decode()).encode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position 0: invalid start byte ``` ##### System information Mitmproxy: 3.0.0.dev0004 (commit 68c32d8) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-109-generic-x86_64-with-Ubuntu-16.04-xenial
Well the problem is that we are assuming the content to be of `utf-8` type here right? as mentioned before by @mhils let's use `get_text` Well the problem is that we are assuming the content to be of `utf-8` type here right? as mentioned before by @mhils let's use `get_text`
2018-02-15T03:13:58
mitmproxy/mitmproxy
2,870
mitmproxy__mitmproxy-2870
[ "2869" ]
baf4b5dc03c3b87fbef6e5df422eb7654594978f
diff --git a/mitmproxy/platform/linux.py b/mitmproxy/platform/linux.py --- a/mitmproxy/platform/linux.py +++ b/mitmproxy/platform/linux.py @@ -1,12 +1,34 @@ import socket import struct +import typing -# Python socket module does not have this constant +# Python's socket module does not have these constants SO_ORIGINAL_DST = 80 +SOL_IPV6 = 41 -def original_addr(csock: socket.socket): - odestdata = csock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16) - _, port, a1, a2, a3, a4 = struct.unpack("!HHBBBBxxxxxxxx", odestdata) - address = "%d.%d.%d.%d" % (a1, a2, a3, a4) - return address, port +def original_addr(csock: socket.socket) -> typing.Tuple[str, int]: + # Get the original destination on Linux. + # In theory, this can be done using the following syscalls: + # sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16) + # sock.getsockopt(SOL_IPV6, SO_ORIGINAL_DST, 28) + # + # In practice, it is a bit more complex: + # 1. We cannot rely on sock.family to decide which syscall to use because of IPv4-mapped + # IPv6 addresses. If sock.family is AF_INET6 while sock.getsockname() is ::ffff:127.0.0.1, + # we need to call the IPv4 version to get a result. + # 2. We can't just try the IPv4 syscall and then do IPv6 if that doesn't work, + # because doing the wrong syscall can apparently crash the whole Python runtime. + # As such, we use a heuristic to check which syscall to do. + is_ipv4 = "." in csock.getsockname()[0] # either 127.0.0.1 or ::ffff:127.0.0.1 + if is_ipv4: + # the struct returned here should only have 8 bytes, but invoking sock.getsockopt + # with buflen=8 doesn't work. + dst = csock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16) + port, raw_ip = struct.unpack_from("!2xH4s", dst) + ip = socket.inet_ntop(socket.AF_INET, raw_ip) + else: + dst = csock.getsockopt(SOL_IPV6, SO_ORIGINAL_DST, 28) + port, raw_ip = struct.unpack_from("!2xH4x16s", dst) + ip = socket.inet_ntop(socket.AF_INET6, raw_ip) + return ip, port
Inability to connect to ipv6 websites through mitmproxy from ipv6 network. ##### Steps to reproduce the problem: 1. Follow [instructions](https://github.com/mitmproxy/mitmproxy/blob/master/docs/transparent/linux.rst) to setup transparent proxy on Linux on my own machine, substituting PREROUTING in the iptables ruleset with OUTPUT. 2. Run `mitmdump --mode transparent` 3. Navigate to ipv4 site (e.g. espn.com) and ipv6 site (e.g. facebook.com). I've done this from two networks. On one network, I have an ipv6 address (according to http://test-ipv6.com/). On the other network, I do not have an ipv6 address. + ipv4 network: Able to connect to both espn.com and facebook.com + ipv6 network: Only able to connect to espn.com. Additionally, when I use http://test-ipv6.com after doing the first two steps above, the website can no longer find my ipv6 address. On the ipv6 network, I receive a message saying the following: ``` Client connection was killed because allow_remote option is set to false, client IP was not a private IP and proxyauth was not set. To allow remote connections set allow_remote option to true or set proxyauth option. [2601:246:100:cefc:7da3:3d6c:6195:5f1f]:42868: Connection killed [2601:246:100:cefc:7da3:3d6c:6195:5f1f]:42868: clientdisconnect ``` When I set the allow_remote option to be true (`mitmproxy --mode transparent --set allow_remote=true`), I now receive the following message: ``` [2601:246:100:cefc:7da3:3d6c:6195:5f1f]:57032: Transparent mode failure: FileNotFoundError(2, ‘No such file or directory’) ``` ##### Any other comments? What have you tried so far? I should try putting mitmproxy in a VM or Docker container. Then, I think I would instead have to use the PREROUTING chain. If the transparent proxy works from the VM/Docker container, this would indicate that the problem has to do with configuration when using the OUTPUT chain. I think it's reasonable that mitmproxy should support ipv6 when run on your own computer. If we can figure out what the problem is, I'd be happy to submit a pull request to the Linux transparent proxy documentation with more explicit instructions on how to set up mitmproxy. Apologies if this is a better fit in discourse, but I think this issue at the very least reflects something which could be improved in the transparent proxy documentation. One hacky option would be to shut down ipv6 altogether through configuration, but I haven't figured out how to make it work. Another possibility is that this has to do with [router advertisements](http://strugglers.net/~andy/blog/2011/09/04/linux-ipv6-router-advertisements-and-forwarding/), but simply setting the accept_ra flag to be equal to two did not work for me. ##### System information Mitmproxy: 3.0.0.dev1179 (commit 6d8731e) Python: 3.6.4 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-21-generic-x86_64-with-debian-stretch-sid <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Thanks for the fantastic write-up! The `FileNotFoundError` in transparent mode is a really weird one, because the only function that could trigger that is `mitmproxy.platform.linux.original_addr`, which doesn't open any files... Can you verify that this is indeed triggered by [linux.py#L9](https://github.com/mitmproxy/mitmproxy/blob/baf4b5dc03c3b87fbef6e5df422eb7654594978f/mitmproxy/platform/linux.py#L9)? I think I made an important omission in writing up the issue, which is that I've usually been passing a script to mitmproxy, and this write up is based off errors received when passing the script. So, it's more likely that this is being triggered [here](https://github.com/mitmproxy/mitmproxy/blob/6d8731e144eaec2aaf2120c21969c9228b7af95a/mitmproxy/addons/script.py). It's still not obvious how ipv4/ipv6 would affect triggering the error here. I'm pretty sure I also encountered problems when not passing the script, but I'm now I'm a bit less confident. I'll have access to the ipv6 network tonight, and I'll try it again with and without a script. Not sure what your script does, but the code path for "Transparent mode failure" is pretty clear: https://github.com/mitmproxy/mitmproxy/blob/568f40c810f4de60f10bd814608fde8268ef7733/mitmproxy/proxy/modes/transparent_proxy.py#L12-L15 https://github.com/mitmproxy/mitmproxy/blob/568f40c810f4de60f10bd814608fde8268ef7733/mitmproxy/platform/__init__.py#L20-L23 https://github.com/mitmproxy/mitmproxy/blob/568f40c810f4de60f10bd814608fde8268ef7733/mitmproxy/platform/linux.py#L8-L12 You're right - I got fixated on the FileNotFoundError, since the only place it shows up in the code is in [script.py](https://github.com/mitmproxy/mitmproxy/blob/6d8731e144eaec2aaf2120c21969c9228b7af95a/mitmproxy/addons/script.py). [The script](https://github.com/aniketpanjwani/chomper/blob/master/chomper/filter.py) just adjusts the response for particular URLS. So, I'm not entirely sure how to verify that it is being triggered by linux.py. Is there some sort of debug mode I can use to drop down to pdb in case of an error? I have two additional things to report: 1. I followed [these instructions](https://community.rackspace.com/products/f/public-cloud-forum/5110/how-to-prefer-ipv4-over-ipv6-in-ubuntu-and-centos) to get my operating system to prefer ipv4 over ipv6. After following these instructions, I am now able to see in mitmproxy all the dual-stack websites such as facebook and instagram which I was previously not seeing. 2. [One VPN](https://helpdesk.privateinternetaccess.com/hc/en-us/articles/232324908-Why-Do-You-Block-IPv6-) claims that they "do not use ipv6 as the current implementations are insecure and could potentially compromise your privacy and security", and that "most VPN software fails to direct IPv6 traffic through the VPN tunnel, so when you connect to an IPv6 enabled website, your browser will make an IPv6 DNS request outside the VPN, which is therefore handled by your ISP". They don't really explain why this occurs, but it's possible that whatever is inherent in ipv6 that makes its use difficult with VPNs is also the issue preventing its use as a transparent proxy. I really know very little about computer networks, so I'm just reasoning by induction. > So, I'm not entirely sure how to verify that it is being triggered by linux.py. Is there some sort of debug mode I can use to drop down to pdb in case of an error? Assuming you have installed mitmproxy from source, the easiest form of debugging would be to add print statements in linux.py. pdb works as well of course, you can call that from an addon in mitmdump so that the UI is out of the way or use https://github.com/mitmproxy/mitmproxy/blob/master/examples/complex/remote_debug.py. And no, there's no particular reason why IPv6 DNS should behave differently. It's very likely possible that our `getsockopt` call doesn't work for IPv6, but I'm quite confused why that triggers a FileNotFound. Ah, it looks like @chadbrubaker was ahead of us: https://github.com/google/nogotofail/commit/c73070ca3098faab2994a83a9249d7c973151aa4. Could you check if applying this fix solves it? Oh cool! I'll get to this in the next few hours. Getting this error when installing from source as per [instructions](https://github.com/mitmproxy/mitmproxy#development-setup): ``` + echo Creating dev environment in ./venv... Creating dev environment in ./venv... + python3 -m venv venv Error: Command '['/home/aniket/personal/other/mitmproxy/venv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1. ``` If I install the requirements from pipenv, will it still be the case that mitmproxy is installed as "editable" (so that it responds to my pdb entries)? I'll try it out... I got the environment working. Here's what I tried - copying @chadbrubaker as closely as possible: ``` import socket import struct # Python socket module does not have this constant SO_ORIGINAL_DST = 80 def original_addr(csock: socket.socket): family = csock.family if family == socket.AF_IFNET: odestdata = csock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 28) elif family == socket.AF_INET6: SOL_IPV6 = 41 odestdata = csock.getsockopt(SOL_IPV6, SO_ORIGINAL_DST, 64) _, port, a1, a2, a3, a4 = struct.unpack("!HHBBBBxxxxxxxx", odestdata) address = "%d.%d.%d.%d" % (a1, a2, a3, a4) return address, port ``` I get an error saying `'socket' has no attribute 'AF_INET'`. Any thoughts? Also, when I stick a `pdb.set_trace()` inside linux.py, I'm able to find `socket.AF_INET`. Some sort of namespace error going on... `if family == socket.AF_IFNET:` <- typo Fixed the typo, but still getting the same TransparentModeFailure. Still a FileNotFound? Yep. Can you get on Slack so that we can shorten turnaround times? Sure thing. Ok, this turned out to be much more of a rabbit hole than I expected. 🐇 1. `sock.getsockopt(SOL_IPV6, SO_ORIGINAL_DST, 28)` is generally the right thing we need to do to support IPv6. 2. Surprise: On IPv6 networks this now breaks IPv4 connections: `sock.family` is `AF_INET6`, `peername` is an IPv4-mapped `::ffff:192.168.0.102`, and the syscall fails. If we observe an IPv4-mapped IPv6 address, we do need to use the original IPv4 syscall. 🙃 3. Biggest surprise: If we call `getsockopt` with arguments for the wrong address type, @aniketpanjwani can reliably crash his Python runtime. Example code: ```python try: dst = sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16) print("IPv4: {}".format(dst)) port, raw_ip = struct.unpack_from("!2xH4s", dst) ip = socket.inet_ntop(socket.AF_INET, raw_ip) except Exception: dst = sock.getsockopt(SOL_IPV6, SO_ORIGINAL_DST, 28) print("IPv4 failed, IPv6: {}".format(dst)) port, raw_ip = struct.unpack_from("!2xH4x16s", dst) ip = socket.inet_ntop(socket.AF_INET6, raw_ip) ``` 4. Overall, the solution seems to be something like this: ```python import socket import struct import typing # Python's socket module does not have these constants SO_ORIGINAL_DST = 80 SOL_IPV6 = 41 def original_addr(sock: socket.socket) -> typing.Tuple[str, int]: # Even if sock.family is AF_INET6, we can't be sure that we actually # need to call getsockopt(SOL_IPV6, SO_ORIGINAL_DST, 28): # For some reason we may have to deal with IPv4-mapped IPv6 addresses here, # in which case only the IPv4 getsockopt call works. # As an additional bonus, we can't just try the IPv4 one and then do IPv6 if that doesn't work, # because doing the wrong call apparently crashes the whole Python runtime. # As such, we use getsockname() as a heuristic to check if we need to go with IPv4. is_ipv4 = "." in sock.getsockname()[0] # either 127.0.0.1 or ::ffff:127.0.0.1 if is_ipv4: # the struct returned here should only have 8 bytes, but invoking with buflen=8 doesn't work. dst = sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16) port, raw_ip = struct.unpack_from("!2xH4s", dst) ip = socket.inet_ntop(socket.AF_INET, raw_ip) else: dst = sock.getsockopt(SOL_IPV6, SO_ORIGINAL_DST, 28) port, raw_ip = struct.unpack_from("!2xH4x16s", dst) ip = socket.inet_ntop(socket.AF_INET6, raw_ip) return ip, port ``` I'll check this tomorrow with a fresh mind and then add tests and submit a PR. Thanks again for the help debugging, @aniketpanjwani! 🍰
2018-02-16T13:43:27
mitmproxy/mitmproxy
2,875
mitmproxy__mitmproxy-2875
[ "2872" ]
18384eecbd8fafca87d7ecaa79d366a5df1063e0
diff --git a/mitmproxy/tools/console/grideditor/col_text.py b/mitmproxy/tools/console/grideditor/col_text.py --- a/mitmproxy/tools/console/grideditor/col_text.py +++ b/mitmproxy/tools/console/grideditor/col_text.py @@ -28,7 +28,7 @@ def blank(self): class EncodingMixin: def __init__(self, data, encoding_args): self.encoding_args = encoding_args - super().__init__(data.encode(*self.encoding_args)) + super().__init__(data.__str__().encode(*self.encoding_args)) def get_data(self): data = super().get_data()
Mitmproxy crashes, when we try to write a value from file into grideditor cell ##### Steps to reproduce the problem: 1. Create a file. Put inside: ``` abc ``` 2. Run mitmproxy. 3. Press `n` -> `Enter` -> `Enter` -> `e` -> `cookies`. You will get into `cookies` grideditor. 4. Press `a` -> `Esc` -> `r` (or `R`, also relevant for it). 5. Input the path to the file with `abc`: `console.grideditor.load` `~/your_file_with_abc` -> `Enter`. You will see: ``` 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 710, in _loop self._entering_idle() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 671, in _entering_idle callback() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 564, in entering_idle self.draw_screen() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 578, in draw_screen canvas = self._topmost_widget.render(self.screen_size, focus=True) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/decoration.py", line 225, in render canv = self._original_widget.render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 1750, in render canv = get_delegate(self).render(size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1083, in render focus and self.focus_part == 'body') File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 141, in cached_render canv = fn(self, size, focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 455, in render (maxcol, maxrow), focus=focus) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 340, in calculate_visible focus_widget, focus_pos = self.body.get_focus() File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 227, in get_focus self.lst[self.focus] File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 83, in __init__ w = self.editor.columns[i].Display(v) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/col_text.py", line 18, in Display return TDisplay(data, self.encoding_args) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/col_text.py", line 31, in __init__ super().__init__(data.encode(*self.encoding_args)) AttributeError: 'bytes' object has no attribute 'encode' ``` ##### Any other comments? What have you tried so far? This bug is relevant for cookies, form, path, query and set-cookies grideditors. I didn't check carefully, but it seems to be relevant for v2.0.2 as well. ##### System information Mitmproxy: 3.0.0.dev113 (commit 93425d4) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial
2018-02-19T04:13:11
mitmproxy/mitmproxy
2,886
mitmproxy__mitmproxy-2886
[ "2829" ]
95c160ac131e235644c12795dc66b46f9b4478cd
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 @@ -159,13 +159,17 @@ def _read_set_cookie_pairs(s: str, off=0) -> Tuple[List[TPairs], int]: if len(rhs) <= 3: trail, off = _read_value(s, off + 1, ";,") rhs = rhs + "," + trail - if rhs or lhs: + + # as long as there's a "=", we consider it a pair + pairs.append([lhs, rhs]) + + elif lhs: pairs.append([lhs, rhs]) - # comma marks the beginning of a new cookie - if off < len(s) and s[off] == ",": - cookies.append(pairs) - pairs = [] + # comma marks the beginning of a new cookie + if off < len(s) and s[off] == ",": + cookies.append(pairs) + pairs = [] off += 1
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 @@ -142,6 +142,27 @@ def test_cookie_roundtrips(): def test_parse_set_cookie_pairs(): pairs = [ + [ + "=", + [[ + ["", ""] + ]] + ], + [ + "=;foo=bar", + [[ + ["", ""], + ["foo", "bar"] + ]] + ], + [ + "=;=;foo=bar", + [[ + ["", ""], + ["", ""], + ["foo", "bar"] + ]] + ], [ "=uno", [[
Incorrect displaying of set-cookie attributes, if no name-value pairs were set in set-cookie header editor ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `n` -> `Enter` -> `Enter` -> `e` -> `set-cookies` 3. Press `a` to add a new row. 4. Choose `Attributes` column and enter subeditor. 5. Add any name-value pair, for example `a 1`. 6. Go to flowview tab by pressing `q` twice. You will see this in Response tab: ![image](https://user-images.githubusercontent.com/20267977/35624324-5704d498-0697-11e8-8352-6b691bcf0507.png) I am not sure it is correct to display just `=` without anything 7. Press `e` -> `set-cookies`. You will see, that name-value from `Attributes` column moved to high-level name-value: ![image](https://user-images.githubusercontent.com/20267977/35624767-a2dc5e80-0698-11e8-8206-397f98d933b3.png) `set-cookies` was changed in Response tab as well. Strange behaviour. ##### Any other comments? What have you tried so far? This small bug is relevant for 2.0.x version as well. ##### System information Mitmproxy: 3.0.0.dev75 (commit 02d2ef7) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial
Hi. I am new to open source and would like to contribute to mitmproxy. Can I work on this issue? @tran-tien-dat Hi! Please, take it, if you want :) I have found the cause the problem. It is around this part of the code: https://github.com/mitmproxy/mitmproxy/blob/326bb546da214eb2c3ca82f9c506f3c051b1e660/mitmproxy/net/http/cookies.py#L143-L165 `lhs` and `rhs` are respectively variables to store the name and value of the cookie or the attribute. They are added to `pairs` in line 165. The code will interpret the first pair as the name and value of the cookie, and the remaining pairs are interpreted as attributes. As can be seen from the code, line 165 is only reached if `lhs` is not an empty string. Thus if we specify an empty string as the name of the cookie, weird behaviours will occur. In particular, if we leave both name and value of the cookie to be empty, then the 1st pair to be added is the name/value of the attribute, so they are "pushed higher up" to become the name/value of the cookie. Besides, if we just leave the name empty, while fill in something for the value of the cookie, mitmproxy will crash. So the problem here is because of not validating the `Set-Cookie` header. I think when mitmproxy parse the `Set-Cookie` header (i.e. in `mitmproxy.net.http.cookies._read_set_cookie_pairs` quoted above), it should only parse valid header. If the `Set-Cookie` header is invalid and the user wants to edit it, mitmproxy should tell the user that the header is invalid and allows editing of the raw header instead of using the current grid editor. I will work on an implementation of this idea.
2018-02-21T12:06:54
mitmproxy/mitmproxy
2,888
mitmproxy__mitmproxy-2888
[ "2885" ]
95c160ac131e235644c12795dc66b46f9b4478cd
diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -44,8 +44,13 @@ def process_options(parser, opts, args): print(debug.dump_system_info()) sys.exit(0) if args.quiet or args.options or args.commands: + # also reduce log verbosity if --options or --commands is passed, + # we don't want log messages from regular startup then. args.verbosity = 'error' args.flow_detail = 0 + if args.verbose: + args.verbosity = 'debug' + args.flow_detail = 2 adict = {} for n in dir(args):
Verbose mode not working in v3.0.0 RC2 ##### Steps to reproduce the problem: 1. Start mitmdump with -v or --verbose flag 2. No DEBUG level logs prints on standard output ##### Any other comments? What have you tried so far? In old stable version (2.0.2) the same steps produce desired output. ##### System information Mitmproxy: 3.0.0.dev1136 (commit 15f525e) Python: 3.6.3 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-3.16.0-5-amd64-x86_64-with-debian-8.9
Good catch, thanks! We apparently need to handle this here: https://github.com/mitmproxy/mitmproxy/blob/da4c1ee625a3451b58c69454ecd5f4faf3cb67d4/mitmproxy/tools/main.py#L42-L48
2018-02-21T21:23:18
mitmproxy/mitmproxy
2,902
mitmproxy__mitmproxy-2902
[ "2901" ]
18384eecbd8fafca87d7ecaa79d366a5df1063e0
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 @@ -10,6 +10,7 @@ import tempfile import traceback import typing # noqa +import contextlib import urwid @@ -102,6 +103,16 @@ def cb(*_): return callback(*args) self.loop.set_alarm_in(seconds, cb) + @contextlib.contextmanager + def uistopped(self): + self.loop.stop() + try: + yield + finally: + self.loop.start() + self.loop.screen_size = None + self.loop.draw_screen() + def spawn_editor(self, data): text = not isinstance(data, bytes) fd, name = tempfile.mkstemp('', "mproxy", text=text) @@ -111,17 +122,16 @@ def spawn_editor(self, data): c = os.environ.get("EDITOR") or "vi" cmd = shlex.split(c) cmd.append(name) - self.ui.stop() - try: - subprocess.call(cmd) - except: - signals.status_message.send( - message="Can't start editor: %s" % " ".join(c) - ) - else: - with open(name, "r" if text else "rb") as f: - data = f.read() - self.ui.start() + with self.uistopped(): + try: + subprocess.call(cmd) + except: + signals.status_message.send( + message="Can't start editor: %s" % " ".join(c) + ) + else: + with open(name, "r" if text else "rb") as f: + data = f.read() os.unlink(name) return data @@ -153,14 +163,13 @@ def spawn_external_viewer(self, data, contenttype): c = "less" cmd = shlex.split(c) cmd.append(name) - self.ui.stop() - try: - subprocess.call(cmd, shell=shell) - except: - signals.status_message.send( - message="Can't start external viewer: %s" % " ".join(c) - ) - self.ui.start() + with self.uistopped(): + try: + subprocess.call(cmd, shell=shell) + except: + signals.status_message.send( + message="Can't start external viewer: %s" % " ".join(c) + ) os.unlink(name) def set_palette(self, opts, updated):
Body editing is broken. From @kajojify: > Enter request-body/response-body editor, then leave it and try to interact with mitmproxy. Everything was ok with v3.0.0rc2, but v3.0.1 stops reacting on any button. I can reproduce this on WSL - this needs to be fixed ASAP and probably warrants a bugfix release. I'm unfortunately super busy this weekend, so it'd be great if someone could take a closer look.
This is an URWID issue, reported here: https://github.com/urwid/urwid/issues/285 Urwid seems to have had a bit of an internal revolution, and has seen two releases this year (last one before that in 2015!). This is great news. I'll chip in on the Urwid ticket to add our voice. In the meantime, we should pin to 1.3.1, and cut a bugfix release. I'm on cafe wifi today, which means I can't do a release until this afternoon. Let's see if someone beats me to it.
2018-02-23T20:22:28
mitmproxy/mitmproxy
2,919
mitmproxy__mitmproxy-2919
[ "2906" ]
154309b81113695c43e8cc157fe1ec25bc44823f
diff --git a/mitmproxy/utils/arg_check.py b/mitmproxy/utils/arg_check.py --- a/mitmproxy/utils/arg_check.py +++ b/mitmproxy/utils/arg_check.py @@ -11,7 +11,6 @@ --order --no-mouse --reverse ---socks --http2-priority --no-http2-priority --no-websocket @@ -59,6 +58,7 @@ -i -f --filter +--socks """ REPLACEMENTS = { @@ -99,7 +99,8 @@ "--replace": "--replacements", "-i": "--intercept", "-f": "--view-filter", - "--filter": "--view-filter" + "--filter": "--view-filter", + "--socks": "--mode socks5" }
Update socks mode access commandline + documentation (v3.0.2) ##### Steps to reproduce the problem: 1. mitmproxy --socks "--socks is deprecated Please use '--set socks=value' instead" 2. Check online documentation at: https://mitmproxy.org/docs/latest/concepts-modes/#socks-proxy 3. Check mitmproxy --help ##### Any other comments? What have you tried so far? 1. The advice given here doesn't appear to work (no combinations I tried were accepted). 2. The online documentation stops at Socks Proxy (no content) 3. The --help text shows the correct method (--mode socks5) ##### System information Mitmproxy: 3.0.2 Python: 3.5.5rc1 OpenSSL: OpenSSL 1.0.1f 6 Jan 2014 Platform: Linux-2.6.39.4-kat124-ga627d40-armv7l-with-debian-jessie-sid (Android: KatKiss Marshmallow hosting Linux Deploy: Ubuntu Trusty [armhf] using pyenv) <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
2018-02-25T14:29:05
mitmproxy/mitmproxy
2,921
mitmproxy__mitmproxy-2921
[ "2899" ]
10b6f6270b7d8a4ebb3764650697d79758e1f916
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -66,7 +66,6 @@ "certifi>=2015.11.20.1", # no semver here - this should always be on the last release! "click>=6.2, <7", "cryptography>=2.1.4,<2.2", - 'h11>=0.7.0,<0.8', "h2>=3.0.1,<4", "hyperframe>=5.1.0,<6", "kaitaistruct>=0.7,<0.9", @@ -76,7 +75,6 @@ "pyOpenSSL>=17.5,<17.6", "pyparsing>=2.1.3, <2.3", "pyperclip>=1.6.0, <1.7", - "requests>=2.9.1, <3", "ruamel.yaml>=0.13.2, <0.16", "sortedcontainers>=1.5.4, <1.6", "tornado>=4.3, <4.6", @@ -96,6 +94,7 @@ "pytest-timeout>=1.2.1,<2", "pytest-xdist>=1.22,<2", "pytest>=3.3,<4", + "requests>=2.9.1, <3", "tox>=2.3, <3", "rstcheck>=2.2, <4.0", ],
Clean up dependencies Spring cleaning! We currently declare some dependencies which are either unused or can easily be substituted: - h11 - not used at all? - requests - tests + examples only. We should IMHO also eventually consider removing the following dependencies, although that involves a bit of work and shouldn't be in scope for this issue: - pyasn1 - replace with asn1crypto, which is used by cryptography/pyOpenSSL - ldap3 - only used for ldap proxy auth, which should probably live outside of the core once we have a healthy addon system.
Hey, I would love to contribute to resolve this issue. One small doubt, you want to remove `requests` from **install_requires** and add it to dev environment only right? @fristonio Hi there! yes, shifting requests into dev should do the trick. The dev requirements are installed for our CI tests, so that shouldn't cause breakage. Thanks - look forward to your PR. Thanks, @cortesi for early response :) Also for `ldap3` are we planning something on improving the addon system for **mitmproxy**. I don't have much familiarization with the codebase yet. For h11, looks like it's indeed unnecessary. h11 is added in https://github.com/mitmproxy/mitmproxy/pull/2545. That pull request vendored wsproto and wsproto requires h11. wsproto is later unvendored in https://github.com/mitmproxy/mitmproxy/pull/2741, so h11 is not used anymore. /cc @Kriechi Sounds about right, thanks @yan12125 for checking! I didn't check for h11, was looking on task to migrate `pyasn1` to `asn1crypto` first. Thanks a lot, @yan12125 now I don't have to worry about checking for **h11**. Here's a question: will dependency cleanup occur on 3.x or it won't happen before 4.0? I wonder if I should wait for some more days before updating the mitmproxy package at MacPorts. I was looking into porting pyasn1 to asn1crypto, The only place where this library was used is to get the `subjectAltNames` ([DNS alt names](https://github.com/mitmproxy/mitmproxy/blob/154309b81113695c43e8cc157fe1ec25bc44823f/mitmproxy/certs.py#L445)) from the certificates. For this single purpose, I don't think to migrate the dependency is a good idea. We can dig in a little bit more and can remove the use of this library altogether by using another approach to parse DNS alt names. @cortesi @mhils what's your stand on this? @yan12125: No concrete timeline, sorry. @fristonio: We transitively depend on pyasn1crypto through cryptography anyway, so including that is fine. I'd also be happy with a kaitaistruct implementation, no particular preference. @yan12125: To expand on this: - ldap3 will definitely stay until 4.0 (we won't change our addon system in a bugfix release) - h11 is a transitive dependency anyway. - requests may be removed in a bugfix release (but shouldn't impact porting much) - pyasn1 will remain until 4.0 as a transitive dependency of ldap3. Hope that helps, and thanks for porting!
2018-02-25T18:33:52
mitmproxy/mitmproxy
2,945
mitmproxy__mitmproxy-2945
[ "1433" ]
8ea58a432ef0697ad9616a5c7b4c70aa2b2b99c7
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 @@ -94,7 +94,9 @@ def sig_add_log(self, event_store, entry: log.LogEntry): self.start_err = entry else: signals.status_message.send( - message=(entry.level, "{}: {}".format(entry.level.title(), entry.msg)), + message=(entry.level, + "{}: {}".format(entry.level.title(), + str(entry.msg).lstrip())), expire=5 ) 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 @@ -49,7 +49,8 @@ def __init__(self, master): def sig_message(self, sender, message, expire=1): if self.prompting: return - w = urwid.Text(message) + cols, _ = self.master.ui.get_cols_rows() + w = urwid.Text(self.shorten_message(message, cols)) self._w = w if expire: def cb(*args): @@ -60,6 +61,36 @@ def cb(*args): def prep_prompt(self, p): return p.strip() + ": " + def shorten_message(self, msg, max_width): + """ + Shorten message so that it fits into a single line in the statusbar. + """ + if isinstance(msg, tuple): + disp_attr, msg_text = msg + elif isinstance(msg, str): + disp_attr, msg_text = None, msg + else: + return msg + msg_end = "\u2026" # unicode ellipsis for the end of shortened message + prompt = "(more in eventlog)" + + msg_lines = msg_text.split("\n") + first_line = msg_lines[0] + if len(msg_lines) > 1: + # First line of messages with a few lines must end with prompt. + line_length = len(first_line) + len(prompt) + else: + line_length = len(first_line) + + if line_length > max_width: + shortening_index = max(0, max_width - len(prompt) - len(msg_end)) + first_line = first_line[:shortening_index] + msg_end + else: + if len(msg_lines) == 1: + prompt = "" + + return [(disp_attr, first_line), ("warn", prompt)] + def sig_prompt(self, sender, prompt, text, callback, args=()): signals.focus.send(self, section="footer") self._w = urwid.Edit(self.prep_prompt(prompt), text or "")
diff --git a/test/mitmproxy/tools/console/test_statusbar.py b/test/mitmproxy/tools/console/test_statusbar.py --- a/test/mitmproxy/tools/console/test_statusbar.py +++ b/test/mitmproxy/tools/console/test_statusbar.py @@ -1,3 +1,5 @@ +import pytest + from mitmproxy import options from mitmproxy.tools.console import statusbar, master @@ -31,3 +33,29 @@ def test_statusbar(monkeypatch): bar = statusbar.StatusBar(m) # this already causes a redraw assert bar.ib._w + + [email protected]("message,ready_message", [ + ("", [(None, ""), ("warn", "")]), + (("info", "Line fits into statusbar"), [("info", "Line fits into statusbar"), + ("warn", "")]), + ("Line doesn't fit into statusbar", [(None, "Line doesn'\u2026"), + ("warn", "(more in eventlog)")]), + (("alert", "Two lines.\nFirst fits"), [("alert", "Two lines."), + ("warn", "(more in eventlog)")]), + ("Two long lines\nFirst doesn't fit", [(None, "Two long li\u2026"), + ("warn", "(more in eventlog)")]) +]) +def test_shorten_message(message, ready_message): + o = options.Options() + m = master.ConsoleMaster(o) + ab = statusbar.ActionBar(m) + assert ab.shorten_message(message, max_width=30) == ready_message + + +def test_shorten_message_narrow(): + o = options.Options() + m = master.ConsoleMaster(o) + ab = statusbar.ActionBar(m) + shorten_msg = ab.shorten_message("error", max_width=4) + assert shorten_msg == [(None, "\u2026"), ("warn", "(more in eventlog)")]
console: notifications cope very poorly with long data ##### Steps to reproduce the problem: When we send a long notification to the statusbar - e.g. a traceback from some internal error - the statusbar gets messed up. We should snip this to the first line, and invite the user to view the rest in the event log. This behaviour can be seen in, e.g. #1431
Working on it.
2018-03-02T22:07:30
mitmproxy/mitmproxy
2,946
mitmproxy__mitmproxy-2946
[ "2818" ]
9760396a3785290db944586fa9bc5118f43f50d4
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 @@ -30,12 +30,14 @@ def __init__( self.focus_changed() def focus_changed(self): + cols, _ = self.master.ui.get_cols_rows() if self.master.view.focus.flow: self._w = common.format_flow( self.master.view.focus.flow, False, extended=True, - hostheader=self.master.options.showhost + hostheader=self.master.options.showhost, + max_url_len=cols, ) else: self._w = urwid.Pile([])
It is difficult to get information from request/response/detail tab, if url is very-very long ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Make a request with pathoc: `pathoc -c example.com:80 localhost:8080 'get:/SOMETHING VERY LONG'` 3. Enter the corresponding flow. You won't be able to see request/response/detail of the flow without changing size of your window. ![image](https://user-images.githubusercontent.com/20267977/35508608-a7e26636-04f9-11e8-96e6-2627d0b8d1f0.png) But if we decide to make a request with url over for example 10k length, even changing the size of window won't help you to see request/response/detail tab. ##### Any other comments? What have you tried so far? About maximum length of a URL https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers ##### System information Mitmproxy: 3.0.0.dev64 (commit 6dd336f) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial
Maybe I can work on this? My initial thoughts would be to have a maximum URL length, and allow user to select it to see the whole content. @tran-tien-dat: Sure, feel free to. :-) I could not find a way to display the extra-extra long url with user's consent without breaking the accessibility of the UI. But to restore it currently, i have wrapped the url upto allowed maximum columns.
2018-03-03T04:16:46
mitmproxy/mitmproxy
2,956
mitmproxy__mitmproxy-2956
[ "2850" ]
53a9be498ca07f7f90ea4c9d3029a7c0ca9f8663
diff --git a/mitmproxy/command.py b/mitmproxy/command.py --- a/mitmproxy/command.py +++ b/mitmproxy/command.py @@ -1,5 +1,5 @@ """ - This module manges and invokes typed commands. + This module manages and invokes typed commands. """ import inspect import types @@ -131,8 +131,13 @@ def collect_commands(self, addon): for i in dir(addon): if not i.startswith("__"): o = getattr(addon, i) - if hasattr(o, "command_path"): - self.add(o.command_path, o) + try: + is_command = hasattr(o, "command_path") + except Exception: + pass # hasattr may raise if o implements __getattr__. + else: + if is_command: + self.add(o.command_path, o) def add(self, path: str, func: typing.Callable): self.commands[path] = Command(self, path, func)
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 @@ -309,6 +309,31 @@ def empty(self) -> None: pass +class TAttr: + def __getattr__(self, item): + raise IOError + + +class TCmds(TAttr): + def __init__(self): + self.TAttr = TAttr() + + @command.command("empty") + def empty(self) -> None: + pass + + +def test_collect_commands(): + """ + This tests for the error thrown by hasattr() + """ + with taddons.context() as tctx: + c = command.CommandManager(tctx.master) + a = TCmds() + c.collect_commands(a) + assert "empty" in c.commands + + def test_decorator(): with taddons.context() as tctx: c = command.CommandManager(tctx.master)
Add exption handling for hasattr because it could throw Fixed https://github.com/mitmproxy/mitmproxy/issues/2849
I will update it and add test Hi, any update on this? :)
2018-03-04T23:44:26
mitmproxy/mitmproxy
2,971
mitmproxy__mitmproxy-2971
[ "2962" ]
56904e02c36ddd9c08909ba9909f46bf223e3761
diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py --- a/mitmproxy/addons/script.py +++ b/mitmproxy/addons/script.py @@ -5,6 +5,7 @@ import sys import types import typing +import traceback from mitmproxy import addonmanager from mitmproxy import exceptions @@ -36,6 +37,25 @@ def load_script(path: str) -> types.ModuleType: sys.path[:] = oldpath +def script_error_handler(path, exc, msg="", tb=False): + """ + Handles all the user's script errors with + an optional traceback + """ + exception = type(exc).__name__ + if msg: + exception = msg + lineno = "" + if hasattr(exc, "lineno"): + lineno = str(exc.lineno) + log_msg = "in Script {}:{} {}".format(path, lineno, exception) + if tb: + etype, value, tback = sys.exc_info() + tback = addonmanager.cut_traceback(tback, "invoke_addon") + log_msg = log_msg.join(["\n"] + traceback.format_exception(etype, value, tback)) + ctx.log.error(log_msg) + + class Script: """ An addon that manages a single script. @@ -53,7 +73,7 @@ def __init__(self, path): self.last_load = 0 self.last_mtime = 0 if not os.path.isfile(self.fullpath): - raise exceptions.OptionsError('No such script: "%s"' % self.fullpath) + raise exceptions.OptionsError('No such script') @property def addons(self): @@ -128,13 +148,13 @@ def script_run(self, flows: typing.Sequence[flow.Flow], path: mtypes.Path) -> No for evt, arg in eventsequence.iterate(f): ctx.master.addons.invoke_addon(s, evt, arg) except exceptions.OptionsError as e: - raise exceptions.CommandError("Error running script: %s" % e) from e + script_error_handler(path, e, msg=str(e)) def configure(self, updated): if "scripts" in updated: for s in ctx.options.scripts: if ctx.options.scripts.count(s) > 1: - raise exceptions.OptionsError("Duplicate script: %s" % s) + raise exceptions.OptionsError("Duplicate script") for a in self.addons[:]: if a.path not in ctx.options.scripts:
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 @@ -183,9 +183,9 @@ def test_script_run(self): def test_script_run_nonexistent(self): sc = script.ScriptLoader() - with taddons.context(sc): - with pytest.raises(exceptions.CommandError): - sc.script_run([tflow.tflow(resp=True)], "/") + with taddons.context(sc) as tctx: + sc.script_run([tflow.tflow(resp=True)], "/") + tctx.master.has_log("/: No such script") def test_simple(self): sc = script.ScriptLoader() @@ -243,6 +243,18 @@ def test_load_err(self): tctx.invoke(sc, "tick") assert len(tctx.master.addons) == 1 + def test_script_error_handler(self): + path = "/sample/path/example.py" + exc = SyntaxError + msg = "Error raised" + tb = True + with taddons.context() as tctx: + script.script_error_handler(path, exc, msg, tb) + assert tctx.master.has_log("/sample/path/example.py") + assert tctx.master.has_log("Error raised") + assert tctx.master.has_log("lineno") + assert tctx.master.has_log("NoneType") + def test_order(self): rec = tutils.test_data.path("mitmproxy/data/addonscripts/recorder") sc = script.ScriptLoader()
User's script error handler function As discussed with @cortesi on slack, right now whenever a user's script throws an error due to various reasons, it is being handled at different places differently. Therefore we can have a consistent error handler function which can be invoked whenever there is an error This will also handle #2837 #2838 #2839 ### Function Signature `script_error(path, message, lineno, exception)` What function will do >"Error in script XXX:NNN MMM” where XXX is the path as specified by the user (the .path attribute of Script), NNN is a line number if we have one, and MMM is a short message The idea here is to display the above mentioned message in the console app and display the traceback related to the error in the event log.
Hi, I was working on this and now I think of it, I have many doubts. I was thinking that instead of keeping the signature as `script_error(path, message, lineno, exception)` let's keep the signature as `script_error_handler(path, exc, tb = False)` The optional traceback will help us to handle whether to provide the user with the same or not Log: "Error in Script XXX:NNN MMM", XXX=path, NNN=line, MMM=name of the error thrown" The function would roughly look like this ``` def script_error_handler(path, exc, tb=False): """ Handles all the user's script errors with an optional traceback """ exception = type(exc).__name__ lineno = "" if hasattr(exc, "lineno"): lineno = str(exc.lineno) msg = "Error in Script {}:{} {}".format(path, lineno, exception) if tb: etype, value, tback = sys.exc_info() tback = addonmanager.cut_traceback(tback, "invoke_addon") msg = msg.join(["\n"]+traceback.format_exception(etype, value, tback)) ctx.log.error(msg) ``` which can be called like this ``` try: something except Exception as exc: script_error_handler(path, exc) ``` @cortesi what do you think? :confused: I think the line number extraction here works - I think a `lineno` attribute is the common API. My rationale for the short message argument is as follows. In the console app, only the first line (or a portion of the first line) of an error is now displayed, and the user has to switch to the event log for everything else. This makes the first line very valuable, and we need to pack as much information as possible in there. It would be nice for this line to say "Syntax error..." and "Exception raised...", and so forth - and in some cases we might be able to give even better information. That said, the first step here is to centralise, and then we can tweak the presentation later. Play around until you have a solution that feels right - we can then merge and tweak it. Hi, so I had this thought process that since the first line is very critical, we might like to provide the user with the name of the type of error that has been raised and providing any other information in place of this would be a big tradeoff(and fitting more than two words at the end of that line would not be very useful if the user has not maximized the window). Maybe in the eventlog we can do like, the important first line with path,line no, name of exception type, second line a useful message and then our optional traceback
2018-03-07T07:44:40
mitmproxy/mitmproxy
2,991
mitmproxy__mitmproxy-2991
[ "2990" ]
2001184b6c373a2a0ea86a9379f8decf3f7912a5
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 @@ -228,10 +228,8 @@ def get_status(self): r.append("[") r.append(("heading_key", "u")) r.append(":%s]" % self.master.options.stickyauth) - if self.master.options.console_default_contentview != "auto": - r.append("[") - r.append(("heading_key", "M")) - r.append(":%s]" % self.master.options.console_default_contentview) + if self.master.options.console_default_contentview != 'auto': + r.append("[contentview:%s]" % (self.master.options.console_default_contentview)) if self.master.options.has_changed("view_order"): r.append("[") r.append(("heading_key", "o"))
Keybinding ‘M’ erroneously highlighted ##### Steps to reproduce the problem: 1. run `mitmproxy` 2. type `O` to open the options editor 3. move the cursor down to `default_contentview` and press Enter 4. type `4` to select `json` 5. type `q` to return to the flows list 6. the status bar now says “[M:json]” with the ‘M’ highlighted, as if it were a shortcut 7. however, typing `M` invokes “Toggle viewing marked flows” instead ##### Any other comments? What have you tried so far? This is similar to #2953. ##### System information Mitmproxy: 3.0.3 binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-116-generic-x86_64-with-debian-stretch-sid
Thanks for reporting these with fantastic instructions, this is really helpful! For now let's just remove the binding, we can think about adding it back later. If someone wants to tackle the "adding back" part in a second PR, it's a bit more difficult now that shortcuts are user-configurable. We'd need to have a function that returns the current keybinding for a given command, and catch the case where no keybinding is configured (in which case we probably need to display something else, e.g. `[mode:json]`).
2018-03-15T15:34:04
mitmproxy/mitmproxy
2,999
mitmproxy__mitmproxy-2999
[ "2953" ]
3c7725a8ce56ef23f1877313396ad397bd4524f0
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 @@ -191,9 +191,7 @@ def get_status(self): r.append(("heading_key", "H")) r.append("eaders]") if len(self.master.options.replacements): - r.append("[") - r.append(("heading_key", "R")) - r.append("eplacing]") + r.append("[%d replacements]" % len(self.master.options.replacements)) if creplay.count(): r.append("[") r.append(("heading_key", "cplayback"))
No shortcut for replacements editor ##### Steps to reproduce the problem: 1. run `mitmproxy` 2. type `O` to open the options editor 3. move the cursor down to `replacements` and press Enter 4. type `a` then `/~s/foo/bar` to add a replacement, and press Esc to commit 5. type `q` and again `q` to return to the flows list 6. the status bar now says “[Replacing]” with the ‘R’ highlighted, as if it were a shortcut 7. however, typing `R` doesn’t do anything ##### Any other comments? What have you tried so far? It seems like `R` was intended to be a shortcut for the replacements editor (which would be very convenient), but left out. It’s not listed in the online help, either. If it wasn’t intended to be a shortcut, it shouldn’t be highlighted in the status bar. ##### System information Mitmproxy: 3.0.3 binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-116-generic-x86_64-with-debian-stretch-sid
Hi! If someone isn't working on this already, I would like to work on this. So from the above discussion, I am not sure that whether or not would we be needing R as a shortcut . Also, if we need to make it a shortcut, do I need to add a relevant entry here: https://github.com/mitmproxy/mitmproxy/blob/957a630bb5d2fcd6a8ad7092863d19e38307f090/mitmproxy/tools/console/overlay.py#L67 Thanks! Hello, I am not working on this, you would like to ask others as well. @kajojify @fenilgandhi I had a look into it but hit the same dead end. There is a decision to be made here and needs someone more familiar with the code as the wrong one would add inconsistency to the code. @proishan11 Also if you want to you can start looking into it or wait for @kajojify to reply. But if the decision comes in favor of removing the highlight , it can be done here. https://github.com/mitmproxy/mitmproxy/blob/957a630bb5d2fcd6a8ad7092863d19e38307f090/mitmproxy/tools/console/statusbar.py#L162 I am not working on it. Feel free to take it :) Good luck! Thanks to your help @fenilgandhi, I am having no problem in removing the highlight. Also, I want to ask that is there any documentation to get familiar with the code? hey @proishan11, are you working on it or can i take this one ? @fenilgandhi I am not working on this. Feel free to take it :)
2018-03-18T19:43:15
mitmproxy/mitmproxy
3,008
mitmproxy__mitmproxy-3008
[ "2969" ]
623f9b694d9f9ddc9130d03b7ffb079c1c492dc6
diff --git a/mitmproxy/connections.py b/mitmproxy/connections.py --- a/mitmproxy/connections.py +++ b/mitmproxy/connections.py @@ -1,18 +1,18 @@ -import time - import os +import time import typing import uuid -from mitmproxy import stateobject, exceptions from mitmproxy import certs +from mitmproxy import exceptions +from mitmproxy import stateobject from mitmproxy.net import tcp from mitmproxy.net import tls +from mitmproxy.utils import human from mitmproxy.utils import strutils class ClientConnection(tcp.BaseHandler, stateobject.StateObject): - """ A client connection @@ -72,11 +72,10 @@ def __repr__(self): else: alpn = "" - return "<ClientConnection: {tls}{alpn}{host}:{port}>".format( + return "<ClientConnection: {tls}{alpn}{address}>".format( tls=tls, alpn=alpn, - host=self.address[0], - port=self.address[1], + address=human.format_address(self.address), ) def __eq__(self, other): @@ -161,7 +160,6 @@ def finish(self): class ServerConnection(tcp.TCPClient, stateobject.StateObject): - """ A server connection @@ -209,11 +207,10 @@ def __repr__(self): ) else: alpn = "" - return "<ServerConnection: {tls}{alpn}{host}:{port}>".format( + return "<ServerConnection: {tls}{alpn}{address}>".format( tls=tls, alpn=alpn, - host=self.address[0], - port=self.address[1], + address=human.format_address(self.address), ) def __eq__(self, other): diff --git a/mitmproxy/utils/human.py b/mitmproxy/utils/human.py --- a/mitmproxy/utils/human.py +++ b/mitmproxy/utils/human.py @@ -73,11 +73,13 @@ def format_timestamp_with_milli(s): return d.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] -def format_address(address: tuple) -> str: +def format_address(address: typing.Optional[tuple]) -> str: """ This function accepts IPv4/IPv6 tuples and returns the formatted address string with port number """ + if address is None: + return "<no address>" try: host = ipaddress.ip_address(address[0]) if host.is_unspecified:
diff --git a/test/mitmproxy/test_connections.py b/test/mitmproxy/test_connections.py --- a/test/mitmproxy/test_connections.py +++ b/test/mitmproxy/test_connections.py @@ -38,6 +38,9 @@ def test_repr(self): assert 'ALPN' not in repr(c) assert 'TLS' in repr(c) + c.address = None + assert repr(c) + def test_tls_established_property(self): c = tflow.tclient_conn() c.tls_established = True @@ -110,6 +113,9 @@ def test_repr(self): c.tls_established = False assert 'TLS' not in repr(c) + c.address = None + assert repr(c) + def test_tls_established_property(self): c = tflow.tserver_conn() c.tls_established = True diff --git a/test/mitmproxy/utils/test_human.py b/test/mitmproxy/utils/test_human.py --- a/test/mitmproxy/utils/test_human.py +++ b/test/mitmproxy/utils/test_human.py @@ -56,3 +56,4 @@ def test_format_address(): assert human.format_address(("example.com", "54010")) == "example.com:54010" assert human.format_address(("::", "8080")) == "*:8080" assert human.format_address(("0.0.0.0", "8080")) == "*:8080" + assert human.format_address(None) == "<no address>"
Setting View Filter shows Addon Error in Eventlog error: Addon error: Traceback (most recent call last): File "/home/coldfire/Projects/mitmproxy/mitmproxy/addons/view.py", line 521, in update idx = self._view.index(f) File "/home/coldfire/Projects/mitmproxy/venv/lib/python3.6/site-packages/sortedcontainers/sortedlist.py", line 2343, in index raise ValueError('{0!r} is not in list'.format(val)) File "/home/coldfire/Projects/mitmproxy/mitmproxy/http.py", line 182, in __repr__ return s.format(flow=self) File "/home/coldfire/Projects/mitmproxy/mitmproxy/connections.py", line 215, in __repr__ host=self.address[0], TypeError: 'NoneType' object is not subscriptable ##### Steps to reproduce the problem: 1. Open `mitmproxy` 2. set a value for `view_filter` in Options or using the ` : set view_filter={str} ` 3. Open a attached browser and open any url 4. Quit the browser and Open the Eventlog in mitmproxy. ##### Any other comments? What have you tried so far? Another error occuring for the view_filter option. I was working on a fix for #2801 #2951 when i noticed this other error occurs if any value is setup in view_filter. I think it requires a complete patch once and for all. ##### System information Mitmproxy: 4.0.0.dev103 (commit 77ed33b) Python: 3.6.4 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.14.21-1-MANJARO-x86_64-with-arch-Manjaro-Linux
I noticed a weird thing, adding `time.sleep(1)` just before the return statement fixes the problem and no errors are generated. I am not sure why or how is this happening. https://github.com/mitmproxy/mitmproxy/blob/cc00b03554d84a37b55f911a84d70b6d7909c9cb/mitmproxy/connections.py#L212 I'm seeing this too. The error appears onscreen and makes the feature hard to use. Is there a way to hide the error from displaying until a fix is found? Not sure why we have a connection with `address = None` at this point, but in any case we should make `ClientConnection.__repr__` and `ServerConnection.__repr__` robust so that they don't crash in this case. This can be either fixed in those functions directly, or we amend `mitmproxy.util.human.format_address` to also accept `None` and then return `<no address information>` or something alike - both works for me. If someone fixes this, please add a test so that it doesn't happen again! 😃 @mhils I think there is another way, we can handle this. As noticed earlier, if we add `time.sleep(1)` before the return statement, somehow the self.address is set to a actual address value. So instead of handling self.address for `None` , can we check whether self.address is `None` and if it is give it some time set an actual value. if self.address is None: time.sleep(1) return {str} @fenilgandhi I have an assumption concerning this issue. I am not sure it is absolutely correct. As you can see the issue appears when mitmproxy tries to give us a representation of `ServerConnection` object, when `ValueError` is raised inside https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py#L521 For some reasons for some flows `self.address` is still `None`, when we need it to be available in `ServerConnection`. When we write `time.sleep(1)`, we suspend execution of the calling thread for 1 second. **Perhaps** mitmproxy switches to other available thread and this thread set the value for `self.address`. The problem is that suspended thread is `MainThread` and every new case with `self.address is None` almost all mitmproxy functions will stop for 1 second. It is also possible, that for some reasons mitmproxy gets `self.address` with a delay and when we write `time.sleep(1)` we compensate this delay. btw `time.sleep(0.1)` works as well. @kajojify I had the same notion but since i could not find the setter/thread which sets the value during the sleep, so i was not sure how to proceed with this. But if what you are saying is true, we can make sure that the setter method sets a value before the ServerConnection.__repr__ is returned. setting `time.sleep(1)` was just a first instinct, but yeah `time.sleep(0.1)` works well too and if we want a fast temporary fix , we can use it. I can't reproduce this. Here's what I'm doing: 1. Start `mitmproxy` 2. `:set view_filter=foo` 3. switch to second window, enter `curl -x localhost:8080 -k https://google.com/` 4. Press `E` to open the event log. @mhils I reproduced it only using a browser.
2018-03-23T03:28:20
mitmproxy/mitmproxy
3,028
mitmproxy__mitmproxy-3028
[ "3011" ]
b5c3883b7886a73043b6cc292ce4a51066ca260a
diff --git a/mitmproxy/tools/console/keymap.py b/mitmproxy/tools/console/keymap.py --- a/mitmproxy/tools/console/keymap.py +++ b/mitmproxy/tools/console/keymap.py @@ -6,6 +6,7 @@ Contexts = { "chooser", "commands", + "dataviewer", "eventlog", "flowlist", "flowview", diff --git a/mitmproxy/tools/console/overlay.py b/mitmproxy/tools/console/overlay.py --- a/mitmproxy/tools/console/overlay.py +++ b/mitmproxy/tools/console/overlay.py @@ -179,7 +179,7 @@ def layout_popping(self): class DataViewerOverlay(urwid.WidgetWrap, layoutwidget.LayoutWidget): - keyctx = "grideditor" + keyctx = "dataviewer" def __init__(self, master, vals): """
Mitmproxy crashes, when trying to add something to options, which are supported by specific command ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `:` 3. Enter one of these commands: `view.order.options`, `console.edit.focus.options`, `console.flowview.mode.options`, `console.layout.options`, `console.bodyview.options`, `console.key.contexts`. Press `enter`. You will see something like: ![image](https://user-images.githubusercontent.com/20267977/37864892-7f9be626-2f7d-11e8-9e10-5da3b65011dc.png) 4. Press `a` button twice. The traceback appears: ``` Traceback (most recent call last): File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/master.py", line 227, in run self.loop.run() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 286, in run self._run() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 384, in _run self.event_loop.run() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 788, in run self._loop() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 825, in _loop self._watch_files[fd]() File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/raw_display.py", line 404, 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 502, in parse_input callback(processed, processed_codes) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 411, in _update self.process_input(keys) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/main_loop.py", line 511, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 309, in keypress k = super().keypress(size, k) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1131, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/window.py", line 44, in keypress ret = super().keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1131, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 595, in keypress *self.calculate_padding_filler(size, True)), key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1590, in keypress key = self.focus.keypress(tsize, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 2271, in keypress key = w.keypress((mc,) + size[1:], key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/decoration.py", line 386, in keypress return self._original_widget.keypress((maxcol, self.height), key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 342, in keypress self._w.keypress(size, key) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/container.py", line 1131, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/listbox.py", line 999, in keypress key = focus_widget.keypress((maxcol,),key) File "/home/kajoj/Mitmproxy/mitmproxy/mitmproxy/tools/console/grideditor/base.py", line 107, in keypress k = self.edit_col.keypress((w,), k) File "/home/kajoj/Mitmproxy/mitmproxy/venv/lib/python3.5/site-packages/urwid/widget.py", line 1772, in <lambda> keypress = property(lambda self:get_delegate(self).keypress) AttributeError: 'Text' object has no attribute 'keypress' ``` ##### System information Mitmproxy: 4.0.0.dev154 (commit f34932c) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-116-generic-x86_64-with-Ubuntu-16.04-xenial
I am debugging this right now. Hope to provide some more insights in a while :) Now, I actually have some more insights. The fact is, I believe the editor keybindings shouldn't be passed as commands when the focus is on a DataViewer widget, like in the case of the commands listed above. To make things clear, I'll post some screenshots of debugging (sorry for the unnecessary info on screen :P) - state of `edit_col` and `editor` in comparison between "Edit cookies" and `console.key.contexts` editors: `console.key.contexts`: ![image](https://user-images.githubusercontent.com/25264901/38165193-037a6d7c-3510-11e8-9f0a-d0f015d8e554.png) Edit Cookies: ![image](https://user-images.githubusercontent.com/25264901/38165198-0fb040bc-3510-11e8-9124-0251cafdbd89.png) Now, `edit_col` {Display} object calls `keypress()` on its topmost widget, which is {Text}...thus the bug. This is not limited to adding. Deleting rows with `d` or editing in external editors with `e` does not trigger any bug, but (as expected) changes are not persistent, to reflect the fact that editing those fields is not expected. After delete with `d` and edit with `e`: ![image](https://user-images.githubusercontent.com/25264901/38165203-321f2b0e-3510-11e8-9b18-9d42b1d08cf4.png) After view refresh (q and :console.key.contexts): ![image](https://user-images.githubusercontent.com/25264901/38165209-5f152ad2-3510-11e8-98c4-da180af6d85f.png) Those keybindings should not be in that view scope. Is anyone working on it? @madt1m I think nobody works on it :) Take it, if you want.
2018-04-01T23:30:06
mitmproxy/mitmproxy
3,044
mitmproxy__mitmproxy-3044
[ "3038" ]
8e54a365fa9617f3037946538044a9905b422952
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 @@ -333,8 +333,20 @@ def _process_flow(self, f): f.request.scheme ) - try: + def get_response(): self.send_request_headers(f.request) + if f.request.stream: + chunks = self.read_request_body(f.request) + if callable(f.request.stream): + chunks = f.request.stream(chunks) + self.send_request_body(f.request, chunks) + else: + self.send_request_body(f.request, [f.request.data.content]) + + f.response = self.read_response_headers() + + try: + get_response() except exceptions.NetlibException as e: self.log( "server communication error: %s" % repr(e), @@ -357,22 +369,17 @@ def _process_flow(self, f): raise exceptions.ProtocolException( "First and only attempt to get response via HTTP2 failed." ) + elif f.request.stream: + # We may have already consumed some request chunks already, + # so all we can do is signal downstream that upstream closed the connection. + self.send_error_response(408, "Request Timeout") + f.error = flow.Error(repr(e)) + self.channel.ask("error", f) + return False self.disconnect() self.connect() - self.send_request_headers(f.request) - - # This is taken out of the try except block because when streaming - # we can't send the request body while retrying as the generator gets exhausted - if f.request.stream: - chunks = self.read_request_body(f.request) - if callable(f.request.stream): - chunks = f.request.stream(chunks) - self.send_request_body(f.request, chunks) - else: - self.send_request_body(f.request, [f.request.data.content]) - - f.response = self.read_response_headers() + get_response() # call the appropriate script hook - this is an opportunity for # an inline script to set f.stream = True
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 @@ -229,28 +229,14 @@ def test_connection_close(self): p.request("get:'%s'" % response) def test_reconnect(self): - req = "get:'%s/p/200:b@1'" % self.server.urlbase + req = "get:'%s/p/200:b@1:da'" % self.server.urlbase p = self.pathoc() - class MockOnce: - call = 0 - - def mock_once(self, http1obj, req): - self.call += 1 - if self.call == 1: - raise exceptions.TcpDisconnect - else: - headers = http1.assemble_request_head(req) - http1obj.server_conn.wfile.write(headers) - http1obj.server_conn.wfile.flush() - with p.connect(): - with mock.patch("mitmproxy.proxy.protocol.http1.Http1Layer.send_request_headers", - side_effect=MockOnce().mock_once, autospec=True): - # Server disconnects while sending headers but mitmproxy reconnects - resp = p.request(req) - assert resp - assert resp.status_code == 200 + assert p.request(req) + # Server has disconnected. Mitmproxy should detect this, and reconnect. + assert p.request(req) + assert p.request(req) def test_get_connection_switching(self): req = "get:'%s/p/200:b@1'" @@ -1045,22 +1031,6 @@ def test_reconnect(self): request again. """ - class MockOnce: - call = 0 - - def mock_once(self, http1obj, req): - self.call += 1 - - if self.call == 2: - headers = http1.assemble_request_head(req) - http1obj.server_conn.wfile.write(headers) - http1obj.server_conn.wfile.flush() - raise exceptions.TcpDisconnect - else: - headers = http1.assemble_request_head(req) - http1obj.server_conn.wfile.write(headers) - http1obj.server_conn.wfile.flush() - self.chain[0].set_addons(RequestKiller([1, 2])) self.chain[1].set_addons(RequestKiller([1])) @@ -1075,9 +1045,7 @@ def mock_once(self, http1obj, req): assert len(self.chain[0].tmaster.state.flows) == 1 assert len(self.chain[1].tmaster.state.flows) == 1 - with mock.patch("mitmproxy.proxy.protocol.http1.Http1Layer.send_request_headers", - side_effect=MockOnce().mock_once, autospec=True): - req = p.request("get:'/p/418:b\"content2\"'") + req = p.request("get:'/p/418:b\"content2\"'") assert req.status_code == 502
Does not handle upstream closing the connection ##### Steps to reproduce the problem: 1. Use a setup such as redirect_requests.py 2. Send a keepalive request into MITM 3. This is passed onto the upstream server and response returned (fine) 4. Wait a little while - upstream closes the connection with a FIN 5. (MITMproxy did not respond to this) 6. Wait a bit longer and send another request to MITM 7. MITM attempts to send this to the upstream which responds with a RST 8. Client sees a 502 bad gateway error ##### Any other comments? What have you tried so far? In our case we were using https://www.npmjs.com/package/json-server#cli-usage as the upstream server but it appears to be complying with keepalive docs. Just very surprised we are the only people seeing this :-) Workaround for us was to add flow.request.headers['Connection'] = 'close', this closed the upstream connection after each request. ``` GET /config HTTP/1.1 Host: 127.0.0.1 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Linux; Android 7.1.1; Android SDK built for x86 Build/NYC) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding: identity Accept-Language: en-US,en;q=0.8 HTTP/1.1 200 OK X-Powered-By: Express Vary: Origin, Accept-Encoding Access-Control-Allow-Credentials: true Cache-Control: no-cache Pragma: no-cache Expires: -1 X-Content-Type-Options: nosniff Content-Type: application/json; charset=utf-8 Content-Length: 4094 ETag: W/"ffe-YXiFVkdRXmM5eFcp/fDfl4O1X+w" Date: Wed, 04 Apr 2018 12:53:09 GMT Connection: keep-alive { "content": { .... } [ NB: FIN is sent by upstream and received by MITM here] GET /config HTTP/1.1 Host: 127.0.0.1 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Linux; Android 7.1.1; Android SDK built for x86 Build/NYC) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding: identity Accept-Language: en-US,en;q=0.8 If-None-Match: W/"ffe-YXiFVkdRXmM5eFcp/fDfl4O1X+w" [ RST now received] ``` ##### System information Mitmproxy: 3.0.3 Python: 3.6.5 OpenSSL: OpenSSL 1.0.2o 27 Mar 2018 Platform: Darwin-17.5.0-x86_64-i386-64bit
I thought this was a problem with my servers. Thanks for this workaround 👍 Thanks for the super useful bug report! We should re-connect in these cases, not sure why we don't do this anymore. Ok, I found some easy steps to reproduce this: ``` $ pathod $ mitmdump --mode reverse:http://localhost:9999 -vvv $ pathoc localhost:8080 "get:'/p/200:da'" get:/p/200 ``` `git bisect` reveals this was broken in https://github.com/mitmproxy/mitmproxy/commit/9e1902be62ba5a6c8d6d1496b3cb18f7deb0e583.
2018-04-05T13:32:27
mitmproxy/mitmproxy
3,050
mitmproxy__mitmproxy-3050
[ "2839" ]
5e2a1ec23c74e4b75278d36b65f74d565ce7d847
diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py --- a/mitmproxy/addons/script.py +++ b/mitmproxy/addons/script.py @@ -25,6 +25,7 @@ def load_script(path: str) -> types.ModuleType: sys.modules.pop(fullname, None) oldpath = sys.path sys.path.insert(0, os.path.dirname(path)) + m = None try: loader = importlib.machinery.SourceFileLoader(fullname, path) spec = importlib.util.spec_from_loader(fullname, loader=loader) @@ -32,9 +33,11 @@ def load_script(path: str) -> types.ModuleType: loader.exec_module(m) if not getattr(m, "name", None): m.name = path # type: ignore - return m + except Exception as e: + script_error_handler(path, e, msg=str(e)) finally: sys.path[:] = oldpath + return m def script_error_handler(path, exc, msg="", tb=False): @@ -48,11 +51,11 @@ def script_error_handler(path, exc, msg="", tb=False): lineno = "" if hasattr(exc, "lineno"): lineno = str(exc.lineno) - log_msg = "in Script {}:{} {}".format(path, lineno, exception) + log_msg = "in script {}:{} {}".format(path, lineno, exception) if tb: etype, value, tback = sys.exc_info() tback = addonmanager.cut_traceback(tback, "invoke_addon") - log_msg = log_msg.join(["\n"] + traceback.format_exception(etype, value, tback)) + log_msg = log_msg + "\n" + "".join(traceback.format_exception(etype, value, tback)) ctx.log.error(log_msg)
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 @@ -12,18 +12,27 @@ from mitmproxy.test import tutils -def test_load_script(): - ns = script.load_script( - tutils.test_data.path( - "mitmproxy/data/addonscripts/recorder/recorder.py" [email protected] +async def test_load_script(): + with taddons.context() as tctx: + ns = script.load_script( + tutils.test_data.path( + "mitmproxy/data/addonscripts/recorder/recorder.py" + ) ) - ) - assert ns.addons + assert ns.addons - with pytest.raises(FileNotFoundError): script.load_script( "nonexistent" ) + assert await tctx.master.await_log("No such file or directory") + + script.load_script( + tutils.test_data.path( + "mitmproxy/data/addonscripts/recorder/error.py" + ) + ) + assert await tctx.master.await_log("invalid syntax") def test_load_fullname(): diff --git a/test/mitmproxy/data/addonscripts/recorder/error.py b/test/mitmproxy/data/addonscripts/recorder/error.py new file mode 100644 --- /dev/null +++ b/test/mitmproxy/data/addonscripts/recorder/error.py @@ -0,0 +1,7 @@ +""" +This file is intended to have syntax errors for test purposes +""" + +impotr recorder # Intended Syntax Error + +addons = [recorder.Recorder("e")]
Different traceback messages appear, when try to run inappropriate file as a script ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `|`(`shift+\`). Input the path to not script file: `: script.run @focus /home/kajoj/myphoto.JPG` Traceback: ![image](https://user-images.githubusercontent.com/20267977/35767610-4eb01d1c-08f8-11e8-97dc-aca5225fd9a5.png) 2a. `: script.run @focus /home/kajoj/passlist.txt` Traceback: ![image](https://user-images.githubusercontent.com/20267977/35767631-c6d8dafe-08f8-11e8-9413-177fe69f4f51.png) ##### Any other comments? What have you tried so far? I think these aren't only traceback messages, which may appear. We should take a look at this place: https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/script.py#L30 ##### System information Mitmproxy: 3.0.0.dev79 (commit 957a630) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-112-generic-x86_64-with-Ubuntu-16.04-xenial
Hi, If noone else is working on it, I will take this :) I have a question Are we stringent that the script the user is trying to run should be a python file such as `example.py`, or we are giving them the flexibility to run any file until and unless it's contents are python code(which we are doing right now)? I would like to go with the second one @kira0204: Are you referring to the filename extension (e.g. `.py`)? We shouldn't enforce anything in that regard. Yes I was, thanks for the clarification :) Okay since we don't want the user to see all the traceback messages we can use `cut_traceback` with the parameter `_call_with_frames_removed` , I know this is not a neat solution but I am not able to find any solution apart from this :( @kira0204 we can try to handle these exceptions here -> https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/script.py#L26 I know, but I want the user to know what is the issue with the code that he is trying to load and where. If we ignore this and go forward with the handling of the exceptions and display a generic message then the solution becomes neat but we would be disturbing the UX @kira0204 issue about users' code exceptions is #2837 I think the current issue happens only when `loader.exec_module` can't even parse the python file properly @kajojify `loader.exec_module` also executes the module in it's own namespace thus there will be cases which will be user's fault because the code will contain errors. When you talked about #2837 case, `exec_module` did it's part and did not execute `request()` (because namespace), but when you invoked that on the flow it raised an exception. But if we talk about errors like syntax errors or maybe logical errors although these are user's code errors(not just exceptions) then `loader.exec_module` is responsible for it Now, if we handle `loader.exec_module()` if it throws any error, how will we tell user where the error was?
2018-04-10T03:06:03
mitmproxy/mitmproxy
3,056
mitmproxy__mitmproxy-3056
[ "3051" ]
660aa87a2471587f3d8a7597a7397be9006db83f
diff --git a/mitmproxy/addons/readfile.py b/mitmproxy/addons/readfile.py --- a/mitmproxy/addons/readfile.py +++ b/mitmproxy/addons/readfile.py @@ -1,9 +1,11 @@ +import asyncio import os.path import sys import typing from mitmproxy import ctx from mitmproxy import exceptions +from mitmproxy import flowfilter from mitmproxy import io @@ -11,18 +13,38 @@ class ReadFile: """ An addon that handles reading from file on startup. """ + def __init__(self): + self.filter = None + def load(self, loader): loader.add_option( "rfile", typing.Optional[str], None, "Read flows from file." ) + loader.add_option( + "readfile_filter", typing.Optional[str], None, + "Read only matching flows." + ) - def load_flows(self, fo: typing.IO[bytes]) -> int: + def configure(self, updated): + if "readfile_filter" in updated: + filt = None + if ctx.options.readfile_filter: + filt = flowfilter.parse(ctx.options.readfile_filter) + if not filt: + raise exceptions.OptionsError( + "Invalid readfile filter: %s" % ctx.options.readfile_filter + ) + self.filter = filt + + async def load_flows(self, fo: typing.IO[bytes]) -> int: cnt = 0 freader = io.FlowReader(fo) try: for flow in freader.stream(): - ctx.master.load_flow(flow) + if self.filter and not self.filter(flow): + continue + await ctx.master.load_flow(flow) cnt += 1 except (IOError, exceptions.FlowReadException) as e: if cnt: @@ -33,29 +55,34 @@ def load_flows(self, fo: typing.IO[bytes]) -> int: else: return cnt - def load_flows_from_path(self, path: str) -> int: + async def load_flows_from_path(self, path: str) -> int: path = os.path.expanduser(path) try: with open(path, "rb") as f: - return self.load_flows(f) + return await self.load_flows(f) except IOError as e: ctx.log.error("Cannot load flows: {}".format(e)) raise exceptions.FlowReadException(str(e)) from e + async def doread(self, rfile): + try: + await self.load_flows_from_path(ctx.options.rfile) + except exceptions.FlowReadException as e: + raise exceptions.OptionsError(e) from e + finally: + ctx.master.addons.trigger("processing_complete") + def running(self): if ctx.options.rfile: - try: - self.load_flows_from_path(ctx.options.rfile) - except exceptions.FlowReadException as e: - raise exceptions.OptionsError(e) from e - finally: - ctx.master.addons.trigger("processing_complete") + asyncio.get_event_loop().create_task(self.doread(ctx.options.rfile)) class ReadFileStdin(ReadFile): """Support the special case of "-" for reading from stdin""" - def load_flows_from_path(self, path: str) -> int: - if path == "-": - return self.load_flows(sys.stdin.buffer) + async def load_flows_from_path(self, path: str) -> int: + if path == "-": # pragma: no cover + # Need to think about how to test this. This function is scheduled + # onto the event loop, where a sys.stdin mock has no effect. + return await self.load_flows(sys.stdin.buffer) else: - return super().load_flows_from_path(path) + return await super().load_flows_from_path(path) diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -150,8 +150,9 @@ def extra(args): if args.filter_args: v = " ".join(args.filter_args) return dict( - view_filter=v, save_stream_filter=v, + readfile_filter=v, + dumper_filter=v, ) return {} diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -85,6 +85,7 @@ "pydivert>=2.0.3,<2.2", ], 'dev': [ + "asynctest>=0.12.0", "flake8>=3.5, <3.6", "Flask>=0.10.1, <0.13", "mypy>=0.580,<0.581",
diff --git a/test/mitmproxy/addons/test_readfile.py b/test/mitmproxy/addons/test_readfile.py --- a/test/mitmproxy/addons/test_readfile.py +++ b/test/mitmproxy/addons/test_readfile.py @@ -1,7 +1,9 @@ +import asyncio import io from unittest import mock import pytest +import asynctest import mitmproxy.io from mitmproxy import exceptions @@ -38,69 +40,83 @@ def corrupt_data(): class TestReadFile: - @mock.patch('mitmproxy.master.Master.load_flow') - def test_configure(self, mck, tmpdir, data, corrupt_data): + def test_configure(self): + rf = readfile.ReadFile() + with taddons.context() as tctx: + tctx.configure(rf, readfile_filter="~q") + with pytest.raises(Exception, match="Invalid readfile filter"): + tctx.configure(rf, readfile_filter="~~") + + @pytest.mark.asyncio + async def test_read(self, tmpdir, data, corrupt_data): rf = readfile.ReadFile() with taddons.context(rf) as tctx: tf = tmpdir.join("tfile") - tf.write(data.getvalue()) - tctx.configure(rf, rfile=str(tf)) - assert not mck.called - rf.running() - assert mck.called + with asynctest.patch('mitmproxy.master.Master.load_flow') as mck: + tf.write(data.getvalue()) + tctx.configure( + rf, + rfile = str(tf), + readfile_filter = ".*" + ) + assert not mck.awaited + rf.running() + await asyncio.sleep(0) + assert mck.awaited tf.write(corrupt_data.getvalue()) tctx.configure(rf, rfile=str(tf)) - with pytest.raises(exceptions.OptionsError): - rf.running() + rf.running() + assert await tctx.master.await_log("corrupted") @pytest.mark.asyncio async def test_corrupt(self, corrupt_data): rf = readfile.ReadFile() with taddons.context(rf) as tctx: - with mock.patch('mitmproxy.master.Master.load_flow') as mck: - with pytest.raises(exceptions.FlowReadException): - rf.load_flows(io.BytesIO(b"qibble")) - assert not mck.called + with pytest.raises(exceptions.FlowReadException): + await rf.load_flows(io.BytesIO(b"qibble")) - tctx.master.clear() - with pytest.raises(exceptions.FlowReadException): - rf.load_flows(corrupt_data) - assert await tctx.master.await_log("file corrupted") - assert mck.called + tctx.master.clear() + with pytest.raises(exceptions.FlowReadException): + await rf.load_flows(corrupt_data) + assert await tctx.master.await_log("file corrupted") @pytest.mark.asyncio - async def test_nonexisting_file(self): + async def test_nonexistent_file(self): rf = readfile.ReadFile() with taddons.context(rf) as tctx: with pytest.raises(exceptions.FlowReadException): - rf.load_flows_from_path("nonexistent") + await rf.load_flows_from_path("nonexistent") assert await tctx.master.await_log("nonexistent") class TestReadFileStdin: - @mock.patch('mitmproxy.master.Master.load_flow') - @mock.patch('sys.stdin') - def test_stdin(self, stdin, load_flow, data, corrupt_data): + @asynctest.patch('sys.stdin') + @pytest.mark.asyncio + async def test_stdin(self, stdin, data, corrupt_data): rf = readfile.ReadFileStdin() - with taddons.context(rf) as tctx: - stdin.buffer = data - tctx.configure(rf, rfile="-") - assert not load_flow.called - rf.running() - assert load_flow.called + with taddons.context(rf): + with asynctest.patch('mitmproxy.master.Master.load_flow') as mck: + stdin.buffer = data + assert not mck.awaited + await rf.load_flows(stdin.buffer) + assert mck.awaited - stdin.buffer = corrupt_data - tctx.configure(rf, rfile="-") - with pytest.raises(exceptions.OptionsError): - rf.running() + stdin.buffer = corrupt_data + with pytest.raises(exceptions.FlowReadException): + await rf.load_flows(stdin.buffer) + @pytest.mark.asyncio @mock.patch('mitmproxy.master.Master.load_flow') - def test_normal(self, load_flow, tmpdir, data): + async def test_normal(self, load_flow, tmpdir, data): rf = readfile.ReadFileStdin() - with taddons.context(rf): - tfile = tmpdir.join("tfile") - tfile.write(data.getvalue()) - rf.load_flows_from_path(str(tfile)) - assert load_flow.called + with taddons.context(rf) as tctx: + tf = tmpdir.join("tfile") + with asynctest.patch('mitmproxy.master.Master.load_flow') as mck: + tf.write(data.getvalue()) + tctx.configure(rf, rfile=str(tf)) + assert not mck.awaited + rf.running() + await asyncio.sleep(0) + assert mck.awaited
mitmdump v3.0.4 doesn't accept filter for positional argument ##### Steps to reproduce the problem: 1. mitmdump '~u google\.com' and I get: Traceback (most recent call last): File "release/specs/mitmdump", line 3, in <module> File "mitmproxy/tools/main.py", line 155, in mitmdump File "mitmproxy/tools/main.py", line 116, in run File "mitmproxy/optmanager.py", line 212, in update KeyError: 'Unknown options: view_filter' [5149] Failed to execute script mitmdump ##### Any other comments? What have you tried so far? mitmdump --set dumper_filter='~u google\.com' works, but not so handy like v3.0.3 or before. Maybe help text needs update, too. It is saying view_filter option. mitmdump --help usage: mitmdump [options] [filter] positional arguments: filter_args Filter expression, equivalent to setting both the view_filter and save_stream_filter options. ##### System information mitmdump --version Mitmproxy: 3.0.4 binary Python: 3.6.4 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Darwin-16.7.0-x86_64-i386-64bit
Can confirm, on MacOS High Sierra, Windows 10 and Kali Linux (The only linux distribution i had lying around ;) ) ``` Mitmproxy: 3.0.4 Python: 3.6.0 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Darwin-17.4.0-x86_64-i386-64bit ``` ``` Mitmproxy: 3.0.4 Python: 3.6.5 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Windows-10-10.0.16299-SP0 ``` ``` Mitmproxy: 3.0.4 Python: 3.6.5rc1 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Linux-4.13.0-kali1-amd64-x86_64-with-Kali-kali-rolling-kali-rolling ```
2018-04-13T23:53:34
mitmproxy/mitmproxy
3,063
mitmproxy__mitmproxy-3063
[ "3061" ]
754cb6cac9b1db56e2221fa379db014856a4725d
diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -67,7 +67,7 @@ def run( make_parser: typing.Callable[[options.Options], argparse.ArgumentParser], arguments: typing.Sequence[str], extra: typing.Callable[[typing.Any], dict] = None -): # pragma: no cover +) -> master.Master: # pragma: no cover """ extra: Extra argument processing callable which returns a dict of options. @@ -121,7 +121,11 @@ def cleankill(*args, **kwargs): signal.signal(signal.SIGTERM, cleankill) loop = asyncio.get_event_loop() for signame in ('SIGINT', 'SIGTERM'): - loop.add_signal_handler(getattr(signal, signame), master.shutdown) + try: + loop.add_signal_handler(getattr(signal, signame), master.shutdown) + except NotImplementedError: + # Not supported on Windows + pass master.run() except exceptions.OptionsError as e: print("%s: %s" % (sys.argv[0], e), file=sys.stderr) @@ -131,19 +135,18 @@ def cleankill(*args, **kwargs): return master -def mitmproxy(args=None): # pragma: no cover +def mitmproxy(args=None) -> typing.Optional[int]: # pragma: no cover if os.name == "nt": print("Error: mitmproxy's console interface is not supported on Windows. " "You can run mitmdump or mitmweb instead.", file=sys.stderr) - sys.exit(1) - + return 1 assert_utf8_env() - from mitmproxy.tools import console - return run(console.master.ConsoleMaster, cmdline.mitmproxy, args) + run(console.master.ConsoleMaster, cmdline.mitmproxy, args) + return None -def mitmdump(args=None): # pragma: no cover +def mitmdump(args=None) -> typing.Optional[int]: # pragma: no cover from mitmproxy.tools import dump def extra(args): @@ -157,11 +160,12 @@ def extra(args): return {} m = run(dump.DumpMaster, cmdline.mitmdump, args, extra) - if m and m.errorcheck.has_errored: - sys.exit(1) - return m + if m and m.errorcheck.has_errored: # type: ignore + return 1 + return None -def mitmweb(args=None): # pragma: no cover +def mitmweb(args=None) -> typing.Optional[int]: # pragma: no cover from mitmproxy.tools import web - return run(web.master.WebMaster, cmdline.mitmweb, args) + run(web.master.WebMaster, cmdline.mitmweb, args) + return None
diff --git a/test/mitmproxy/tools/test_main.py b/test/mitmproxy/tools/test_main.py --- a/test/mitmproxy/tools/test_main.py +++ b/test/mitmproxy/tools/test_main.py @@ -1,18 +1,19 @@ import pytest from mitmproxy.tools import main +from mitmproxy import ctx @pytest.mark.asyncio async def test_mitmweb(event_loop): - m = main.mitmweb([ + main.mitmweb([ "--no-web-open-browser", "-q", "-p", "0", ]) - await m._shutdown() + await ctx.master._shutdown() @pytest.mark.asyncio async def test_mitmdump(): - m = main.mitmdump(["-q", "-p", "0"]) - await m._shutdown() + main.mitmdump(["-q", "-p", "0"]) + await ctx.master._shutdown()
add_signal_handler is strictly UNIX only. https://github.com/mitmproxy/mitmproxy/blob/4e126c0fbaafffd23e1a80926de6a99c897f9af0/mitmproxy/tools/main.py#L124 According to the `asyncio` documentation for [Python 3.6](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.add_signal_handler) , `add_signal_handler` is supported for UNIX system only. I haven't experienced or tested this issue but it maybe a potential risk since mitmproxy supports multiple platforms. If someone has a Windows OS and/or some knowledge about asyncio maybe you could verify this.
Although not the best solution , but the best workaround is to add a simple coroutine with call_later of 0.1. Somehow this works well in Windows and CTRL+C can terminate the loop. [Ref](https://stackoverflow.com/questions/24774980/why-cant-i-catch-sigint-when-asyncio-event-loop-is-running/24775107#24775107) Good catch! We need someone on Windows to actually test the behaviour here. The StackOverflow question you included refers to a patch implementing add_signal_handler for the Windows event loops from 3.5 years ago which (sigh) appears never to have been merged. Step one is to catch the `NotImplementedError` around that call and ignore it. I am on Windows and I pulled the commit from 2 days ago and since then, mitmdump and mitmweb weren't working anymore : ![commit_error](https://user-images.githubusercontent.com/15815157/38795371-4bd90854-4158-11e8-9b13-906b4f70c5fe.JPG) I thought it was because of some modifications I made so I didn't make an issue of that and I searched by myself without success. But I just tested your solution of putting a try to catch the "NotImplementedError" : `try: loop.add_signal_handler(getattr(signal, signame), master.shutdown) except NotImplementedError as e: print("ERROR : Method not implemented in Windows.")` and then: ![notimplement_exception](https://user-images.githubusercontent.com/15815157/38795589-1345aac8-4159-11e8-9bd4-f451f7456a9b.JPG) So the behaviour here is that mitmdump and mitmweb are not usable until the exception is catched. ### UPDATE It seems like signal handling is a mess on Windows, and that there is no clean way to make CTRL + C exit the process without an error message, but CTRL + Break seems to do the work. @cortal Thanks for looking at this. Once the exception is caught, does mitmdump exit on ctrl-C? Yes, mitmdump exits on CTRL-C. (I checked with tasklist) And the message you can see from my terminal screenshot is because I set the asyncio logger to DEBUG level to get more information, on CRITICAL level, the message doesn't show.
2018-04-16T20:17:13
mitmproxy/mitmproxy
3,069
mitmproxy__mitmproxy-3069
[ "3067" ]
633023701b9f57b19d6e86af96390575be8ef33a
diff --git a/mitmproxy/net/tcp.py b/mitmproxy/net/tcp.py --- a/mitmproxy/net/tcp.py +++ b/mitmproxy/net/tcp.py @@ -22,8 +22,6 @@ # Python 3.6 for Windows is missing a constant IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) -EINTR = 4 - class _FileLike: BLOCKSIZE = 1024 * 32 @@ -595,14 +593,7 @@ def serve_forever(self, poll_interval=0.1): self.__is_shut_down.clear() try: while not self.__shutdown_request: - try: - r, w_, e_ = select.select( - [self.socket], [], [], poll_interval) - except select.error as ex: # pragma: no cover - if ex[0] == EINTR: - continue - else: - raise + r, w_, e_ = select.select([self.socket], [], [], poll_interval) if self.socket in r: connection, client_address = self.socket.accept() t = basethread.BaseThread( 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 @@ -18,7 +18,6 @@ from mitmproxy import log from mitmproxy import version from mitmproxy import optmanager -from mitmproxy.tools.cmdline import CONFIG_PATH import mitmproxy.tools.web.master # noqa @@ -457,10 +456,11 @@ def put(self): class SaveOptions(RequestHandler): def post(self): - try: - optmanager.save(self.master.options, CONFIG_PATH, True) - except Exception as err: - raise APIError(400, "{}".format(err)) + # try: + # optmanager.save(self.master.options, CONFIG_PATH, True) + # except Exception as err: + # raise APIError(400, "{}".format(err)) + pass class Application(tornado.web.Application): 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 @@ -105,33 +105,21 @@ def _sig_settings_update(self, options, updated): def run(self): # pragma: no cover AsyncIOMainLoop().install() - iol = tornado.ioloop.IOLoop.instance() - http_server = tornado.httpserver.HTTPServer(self.app) http_server.listen(self.options.web_port, self.options.web_iface) - - iol.add_callback(self.start) - web_url = "http://{}:{}/".format(self.options.web_iface, self.options.web_port) self.log.info( "Web server listening at {}".format(web_url), ) - + # FIXME: This should be in an addon hooked to the "running" event, not in master if self.options.web_open_browser: success = open_browser(web_url) if not success: self.log.info( "No web browser found. Please open a browser and point it to {}".format(web_url), ) - try: - iol.start() - except KeyboardInterrupt: - self.shutdown() - - def shutdown(self): - tornado.ioloop.IOLoop.instance().stop() - super().shutdown() + self.run_loop(iol.start) def open_browser(url: str) -> bool:
[mitmweb] CTRL-C not working ##### Steps to reproduce the problem: 1.Start mitmweb 2.Try to shutdown with CTRL-C 3.Nothing happens ##### Any other comments? What have you tried so far? With the signal handler not being implemented on Windows, CTRL-C on mitmweb is not doing anything. On top of that the message "Proxy server listening on ..." doesn't appear anymore. I found this workaround that I tested myself : https://stackoverflow.com/questions/27480967/why-does-the-asyncios-event-loop-suppress-the-keyboardinterrupt-on-windows It's working, it's just that it's not a clean exit of the program ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ![mitmdump_version](https://user-images.githubusercontent.com/15815157/38858134-336ea1ce-422b-11e8-917a-a329e97591ab.JPG) <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
2018-04-17T20:39:34
mitmproxy/mitmproxy
3,070
mitmproxy__mitmproxy-3070
[ "3066" ]
6d5c8781e2894089e96c51bea2ce2158280e4374
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 @@ -235,7 +235,7 @@ def post(self): self.view.clear() bio = BytesIO(self.filecontents) for i in io.FlowReader(bio).stream(): - asyncio.call_soon(self.master.load_flow, i) + asyncio.ensure_future(self.master.load_flow(i)) bio.close()
[mitmweb] asyncio has no attribute call_soon ##### Steps to reproduce the problem: 1.Launch mitmweb 2.Save some flow 3.Load those flows ![asyncio_attribute_error](https://user-images.githubusercontent.com/15815157/38856635-48c7130c-4227-11e8-9019-0caf8f22038c.JPG) ##### Any other comments? What have you tried so far? https://github.com/mitmproxy/mitmproxy/blob/0fa1280daa94729defa8411d86266bd2b52ad0b6/mitmproxy/tools/web/app.py#L238-L239 I replaced this line with `asyncio.ensure_future(self.master.load_flows(i))` to make the loading works. ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ![mitmdump_version](https://user-images.githubusercontent.com/15815157/38857072-93f56a8a-4228-11e8-8fbb-fed4e11c2745.JPG) <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Want to submit a PR for this? Your solution is correct.
2018-04-18T08:35:46
mitmproxy/mitmproxy
3,078
mitmproxy__mitmproxy-3078
[ "3002" ]
5546f0a05ec21db986f0639cee9e89452ba68642
diff --git a/mitmproxy/addons/cut.py b/mitmproxy/addons/cut.py --- a/mitmproxy/addons/cut.py +++ b/mitmproxy/addons/cut.py @@ -1,6 +1,8 @@ import io import csv import typing +import os.path + from mitmproxy import command from mitmproxy import exceptions from mitmproxy import flow @@ -87,7 +89,8 @@ def save( append = False if path.startswith("+"): append = True - path = mitmproxy.types.Path(path[1:]) + epath = os.path.expanduser(path[1:]) + path = mitmproxy.types.Path(epath) try: if len(cuts) == 1 and len(flows) == 1: with open(path, "ab" if append else "wb") as fp: diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -10,7 +10,6 @@ """ import collections import typing -import os import blinker import sortedcontainers @@ -359,9 +358,8 @@ def load_file(self, path: mitmproxy.types.Path) -> None: """ Load flows into the view, without processing them with addons. """ - spath = os.path.expanduser(path) try: - with open(spath, "rb") as f: + with open(path, "rb") as f: for i in io.FlowReader(f).stream(): # Do this to get a new ID, so we can load the same file N times and # get new flows each time. It would be more efficient to just have a diff --git a/mitmproxy/types.py b/mitmproxy/types.py --- a/mitmproxy/types.py +++ b/mitmproxy/types.py @@ -178,7 +178,7 @@ def completion(self, manager: _CommandBase, t: type, start: str) -> typing.Seque return ret def parse(self, manager: _CommandBase, t: type, s: str) -> str: - return s + return os.path.expanduser(s) def is_valid(self, manager: _CommandBase, typ: typing.Any, val: typing.Any) -> bool: return isinstance(val, str)
diff --git a/test/mitmproxy/test_types.py b/test/mitmproxy/test_types.py --- a/test/mitmproxy/test_types.py +++ b/test/mitmproxy/test_types.py @@ -2,6 +2,7 @@ import os import typing import contextlib +from unittest import mock from mitmproxy.test import tutils import mitmproxy.exceptions @@ -69,7 +70,10 @@ def test_path(): b = mitmproxy.types._PathType() assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/foo") == "/foo" assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/bar") == "/bar" + with mock.patch.dict("os.environ", {"HOME": "/home/test"}): + assert b.parse(tctx.master.commands, mitmproxy.types.Path, "~/mitm") == "/home/test/mitm" assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, "foo") is True + assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, "~/mitm") is True assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, 3) is False def normPathOpts(prefix, match):
commands taking a filename should expand home dir (tilde) ##### Steps to reproduce the problem: 1. Open a flow on the response tab. 2. Press "b". 3. When prompted for a filename, enter `~/example`. This says "No such file or directory". Entering "/home/username/example" works. ##### System information <!-- Paste the output of "mitmproxy --version" here. --> Mitmproxy: 3.0.3 Python: 3.6.4 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.15.10-1-ARCH-x86_64-with-arch
Thanks for the issue. ### Tilda support for commands at this moment. | Button | Command | Status | | --- | --- | --- | | `W` | console.command.set save_stream_file | :heavy_check_mark: | | `b` | cut.save | :x: | | `w` | save.file | :heavy_check_mark: | | `e` | export.file | :x: | | - | replay.client.file | :heavy_check_mark: | | - | replay.server.file |:heavy_check_mark: | | `L` | view.load | :heavy_check_mark: | | `L` | options.load | :heavy_check_mark: | | `S` | options.save | :heavy_check_mark: | | `r` | console.grideditor.load | :heavy_check_mark: | | `R` | console.grideditor.load_escaped | :heavy_check_mark: | | `w` | console.grideditor.save | :x: | | `shift+\` | script.run | :heavy_check_mark: | I'll fix this. IIRC at some point it was discussed to have a dedicated `Path` argument type that automatically handles that. Are we tracking that anywhere already? @mhils I only see, that some commands have `path = os.path.expanduser(path)` It looks like @cortesi started hacking on this: https://github.com/mitmproxy/mitmproxy/blob/443409e32bcc28a7f0475d7af42efff03473b72f/examples/addons/commands-paths.py#L17 - not sure if that auto-expands already? > not sure if that auto-expands already? It doesn’t; would be nice if it did.
2018-04-25T23:03:34
mitmproxy/mitmproxy
3,097
mitmproxy__mitmproxy-3097
[ "3096" ]
165a4be7a963262e5a914a45dfb2a91b4c2ee5da
diff --git a/examples/complex/dup_and_replay.py b/examples/complex/dup_and_replay.py --- a/examples/complex/dup_and_replay.py +++ b/examples/complex/dup_and_replay.py @@ -2,7 +2,13 @@ def request(flow): - f = flow.copy() - ctx.master.view.add(f) - f.request.path = "/changed" - ctx.master.replay_request(f, block=True) + # Avoid an infinite loop by not replaying already replayed requests + if flow.request.is_replay: + return + flow = flow.copy() + # Only interactive tools have a view. If we have one, add a duplicate entry + # for our flow. + if "view" in ctx.master.addons: + ctx.master.commands.call("view.add", [flow]) + flow.request.path = "/changed" + ctx.master.commands.call("replay.client", [flow]) diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -293,6 +293,7 @@ def clear_not_marked(self): self._refilter() self.sig_store_refresh.send(self) + @command.command("view.marked.toggle") def add(self, flows: typing.Sequence[mitmproxy.flow.Flow]) -> None: """ Adds a flow to the state. If the flow already exists, it is
duplicate and replay example error Hello I am trying to understand duplicate and replay process so I tried to run dup_and_replay.py but there is something that I keep getting this error Addon error: Traceback (most recent call last): File "dup.py", line 6, in request ctx.master.view.add(f) AttributeError: 'DumpMaster' object has no attribute 'view' Could you please help me
2018-05-04T21:35:32
mitmproxy/mitmproxy
3,099
mitmproxy__mitmproxy-3099
[ "3024" ]
b4f618e801ba0dcf5c59b5c3781eb5b2724133e0
diff --git a/mitmproxy/addons/allowremote.py b/mitmproxy/addons/allowremote.py --- a/mitmproxy/addons/allowremote.py +++ b/mitmproxy/addons/allowremote.py @@ -14,11 +14,13 @@ def load(self, loader): ) def clientconnect(self, layer): - address = layer.client_conn.address + address = ipaddress.ip_address(layer.client_conn.address[0]) + if isinstance(address, ipaddress.IPv6Address): + address = address.ipv4_mapped or address accept_connection = ( ctx.options.allow_remote or - ipaddress.ip_address(address[0]).is_private or + ipaddress.ip_address(address).is_private or ctx.options.proxyauth is not None )
diff --git a/test/mitmproxy/addons/test_allowremote.py b/test/mitmproxy/addons/test_allowremote.py --- a/test/mitmproxy/addons/test_allowremote.py +++ b/test/mitmproxy/addons/test_allowremote.py @@ -5,27 +5,49 @@ from mitmproxy.test import taddons [email protected]("allow_remote, ip, should_be_killed", [ - (True, "192.168.1.3", False), - (True, "122.176.243.101", False), - (False, "192.168.1.3", False), - (False, "122.176.243.101", True), - (True, "::ffff:1:2", False), - (True, "fe80::", False), - (True, "2001:4860:4860::8888", False), - (False, "::ffff:1:2", False), - (False, "fe80::", False), - (False, "2001:4860:4860::8888", True), [email protected]("allow_remote, should_be_killed, address", [ + (True, False, ("10.0.0.1",)), + (True, False, ("172.20.0.1",)), + (True, False, ("192.168.1.1",)), + (True, False, ("1.1.1.1",)), + (True, False, ("8.8.8.8",)), + (True, False, ("216.58.207.174",)), + (True, False, ("::ffff:1.1.1.1",)), + (True, False, ("::ffff:8.8.8.8",)), + (True, False, ("::ffff:216.58.207.174",)), + (True, False, ("::ffff:10.0.0.1",)), + (True, False, ("::ffff:172.20.0.1",)), + (True, False, ("::ffff:192.168.1.1",)), + (True, False, ("fe80::",)), + (True, False, ("2001:4860:4860::8888",)), + (False, False, ("10.0.0.1",)), + (False, False, ("172.20.0.1",)), + (False, False, ("192.168.1.1",)), + (False, True, ("1.1.1.1",)), + (False, True, ("8.8.8.8",)), + (False, True, ("216.58.207.174",)), + (False, True, ("::ffff:1.1.1.1",)), + (False, True, ("::ffff:8.8.8.8",)), + (False, True, ("::ffff:216.58.207.174",)), + (False, False, ("::ffff:10.0.0.1",)), + (False, False, ("::ffff:172.20.0.1",)), + (False, False, ("::ffff:192.168.1.1",)), + (False, False, ("fe80::",)), + (False, True, ("2001:4860:4860::8888",)), ]) @pytest.mark.asyncio -async def test_allowremote(allow_remote, ip, should_be_killed): +async def test_allowremote(allow_remote, should_be_killed, address): + if allow_remote: + # prevent faulty tests + assert not should_be_killed + ar = allowremote.AllowRemote() up = proxyauth.ProxyAuth() with taddons.context(ar, up) as tctx: tctx.options.allow_remote = allow_remote with mock.patch('mitmproxy.proxy.protocol.base.Layer') as layer: - layer.client_conn.address = (ip, 12345) + layer.client_conn.address = address ar.clientconnect(layer) if should_be_killed:
allow_remote=false does not prevent remote access ##### Steps to reproduce the problem: 1. Run mitmproxy on a publicly routable host, with default configuration including `listen_host=""`, `listen_port=8080`, and `allow_remote=false`. 2. From a host on a different network, send a request through that instance of mitmproxy, e.g. with `curl --proxy http://your-host.example:8080` The default `allow_remote=false` should prevent this request from succeeding. However, it is served by mitmproxy just fine. ##### Any other comments? What have you tried so far? I have a laptop sitting in the “DMZ” of a home router, which is globally IPv4 routable. I also have a VPS which is globally IPv4 routable. Both the laptop and the VPS are running Ubuntu 16.04 “Xenial Xerus”. I can reproduce the problem with mitmproxy running on the VPS and curl on the laptop, as well as vice-versa. Both tcpdump and mitmproxy’s own Details pane show the request as originating from a remote network. I only noticed this because I saw strange flows in a mitmproxy instance that I spun up on the laptop. ##### System information Mitmproxy: 3.0.3 binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-116-generic-x86_64-with-debian-stretch-sid
Thanks - I can verify it! Not sure why yet, but the tests and the implementation are not that complex... let me look into that! Looks like the check fails because IPv4 source addresses get mapped into IPv6 address with `::ffff:<IPv4>`, and then it apparently becomes a private address range in https://github.com/python/cpython/blob/10b134a07c898c2fbc5fd3582503680a54ed80a2/Lib/ipaddress.py#L2258.
2018-05-05T11:56:56
mitmproxy/mitmproxy
3,114
mitmproxy__mitmproxy-3114
[ "3113" ]
ab89079c65272a9a2ef4f98d38d0ed39468bc876
diff --git a/examples/complex/tcp_message.py b/examples/complex/tcp_message.py --- a/examples/complex/tcp_message.py +++ b/examples/complex/tcp_message.py @@ -6,23 +6,22 @@ * prints various details for each packet. example cmdline invocation: -mitmdump -T --host --tcp ".*" -q -s examples/tcp_message.py +mitmdump --rawtcp --tcp-host ".*" -s examples/complex/tcp_message.py """ from mitmproxy.utils import strutils from mitmproxy import ctx +from mitmproxy import tcp -def tcp_message(tcp_msg): - modified_msg = tcp_msg.message.replace("foo", "bar") - - is_modified = False if modified_msg == tcp_msg.message else True - tcp_msg.message = modified_msg +def tcp_message(flow: tcp.TCPFlow): + message = flow.messages[-1] + old_content = message.content + message.content = old_content.replace(b"foo", b"bar") ctx.log.info( - "[tcp_message{}] from {} {} to {} {}:\r\n{}".format( - " (modified)" if is_modified else "", - "client" if tcp_msg.sender == tcp_msg.client_conn else "server", - tcp_msg.sender.address, - "server" if tcp_msg.receiver == tcp_msg.server_conn else "client", - tcp_msg.receiver.address, strutils.bytes_to_escaped_str(tcp_msg.message)) + "[tcp_message{}] from {} to {}:\n{}".format( + " (modified)" if message.content != old_content else "", + "client" if message.from_client else "server", + "server" if message.from_client else "client", + strutils.bytes_to_escaped_str(message.content)) )
tcp_message script not working Hi, I tried to execute the TCP message replace script from the doc but it seems is not working. I don't know if this is a issue with the doc script or with mitmproxy. The script was unchanged. ##### Steps to reproduce the problem: 1. mitmdump --mode transparent --tcp-host ".*" -k -s examples/complex/tcp_message.py Loading script: examples/tcp_message.py Proxy server listening at http://*:8080 192.168.1.241:37604: clientconnect ::ffff:192.168.1.241:37604: Certificate verification error for None: hostname 'no-hostname' doesn't match either of '*.local.org', 'local.org' ::ffff:192.168.1.241:37604: Ignoring server verification error, continuing with connection Addon error: Traceback (most recent call last): File "examples/tcp_message.py", line 16, in tcp_message modified_msg = tcp_msg.message.replace("foo", "bar") AttributeError: 'TCPFlow' object has no attribute 'message' 192.168.1.241:37604 -> tcp -> 10.0.0.2:5443 Addon error: Traceback (most recent call last): File "examples/tcp_message.py", line 16, in tcp_message modified_msg = tcp_msg.message.replace("foo", "bar") AttributeError: 'TCPFlow' object has no attribute 'message' 192.168.1.241:37604 <- tcp <- 10.0.0.2:5443 ##### System information <!-- Paste the output of "mitmproxy --version" here. --> mitmdump --version Mitmproxy: 3.0.4 Python: 3.6.0 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Linux-3.19.0-65-generic-x86_64-with-debian-jessie-sid <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Thanks - looks like the example is a bit outdated. I'll send a PR to update it in a few minutes. Thanks, Is possible to post here an update example I really need one.
2018-05-11T09:58:40
mitmproxy/mitmproxy
3,115
mitmproxy__mitmproxy-3115
[ "2787" ]
ce6029b435f3a0ce6269adf38fde6ef50c45c513
diff --git a/mitmproxy/command.py b/mitmproxy/command.py --- a/mitmproxy/command.py +++ b/mitmproxy/command.py @@ -35,9 +35,11 @@ def typename(t: type) -> str: """ Translates a type to an explanatory string. """ + if t == inspect._empty: # type: ignore + raise exceptions.CommandError("missing type annotation") to = mitmproxy.types.CommandTypes.get(t, None) if not to: - raise NotImplementedError(t) + raise exceptions.CommandError("unsupported type: %s" % getattr(t, "__name__", t)) return to.display @@ -58,7 +60,12 @@ def __init__(self, manager, path, func) -> None: if i.kind == i.VAR_POSITIONAL: self.has_positional = True self.paramtypes = [v.annotation for v in sig.parameters.values()] - self.returntype = sig.return_annotation + if sig.return_annotation == inspect._empty: # type: ignore + self.returntype = None + else: + self.returntype = sig.return_annotation + # This fails with a CommandException if types are invalid + self.signature_help() def paramnames(self) -> typing.Sequence[str]: v = [typename(i) for i in self.paramtypes] @@ -133,7 +140,12 @@ def collect_commands(self, addon): pass # hasattr may raise if o implements __getattr__. else: if is_command: - self.add(o.command_path, o) + try: + self.add(o.command_path, o) + except exceptions.CommandError as e: + self.master.log.warn( + "Could not load command %s: %s" % (o.command_path, e) + ) def add(self, path: str, func: typing.Callable): self.commands[path] = Command(self, path, func) diff --git a/mitmproxy/tools/console/commands.py b/mitmproxy/tools/console/commands.py --- a/mitmproxy/tools/console/commands.py +++ b/mitmproxy/tools/console/commands.py @@ -46,12 +46,13 @@ def keypress(self, size, key): class CommandListWalker(urwid.ListWalker): def __init__(self, master): self.master = master - self.index = 0 - self.focusobj = None - self.cmds = list(master.commands.commands.values()) + self.refresh() + + def refresh(self): + self.cmds = list(self.master.commands.commands.values()) self.cmds.sort(key=lambda x: x.signature_help()) - self.set_focus(0) + self.set_focus(self.index) def get_edit_text(self): return self.focus_obj.get_edit_text() @@ -137,6 +138,9 @@ def __init__(self, master): ) self.master = master + def layout_pushed(self, prev): + self.widget_list[0].walker.refresh() + def keypress(self, size, key): if key == "m_next": self.focus_position = (
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 @@ -1,4 +1,5 @@ import typing +import inspect from mitmproxy import command from mitmproxy import flow from mitmproxy import exceptions @@ -55,7 +56,35 @@ def flow(self, f: flow.Flow, s: str) -> None: pass +class Unsupported: + pass + + +class TypeErrAddon: + @command.command("noret") + def noret(self): + pass + + @command.command("invalidret") + def invalidret(self) -> Unsupported: + pass + + @command.command("invalidarg") + def invalidarg(self, u: Unsupported): + pass + + class TestCommand: + def test_typecheck(self): + with taddons.context(loadcore=False) as tctx: + cm = command.CommandManager(tctx.master) + a = TypeErrAddon() + command.Command(cm, "noret", a.noret) + with pytest.raises(exceptions.CommandError): + command.Command(cm, "invalidret", a.invalidret) + with pytest.raises(exceptions.CommandError): + command.Command(cm, "invalidarg", a.invalidarg) + def test_varargs(self): with taddons.context() as tctx: cm = command.CommandManager(tctx.master) @@ -275,6 +304,11 @@ def test_typename(): assert command.typename(mitmproxy.types.Path) == "path" assert command.typename(mitmproxy.types.Cmd) == "cmd" + with pytest.raises(exceptions.CommandError, match="missing type annotation"): + command.typename(inspect._empty) + with pytest.raises(exceptions.CommandError, match="unsupported type"): + command.typename(None) + class DummyConsole: @command.command("view.resolve") @@ -326,7 +360,8 @@ def empty(self) -> None: pass -def test_collect_commands(): [email protected] +async def test_collect_commands(): """ This tests for the error thrown by hasattr() """ @@ -336,6 +371,10 @@ def test_collect_commands(): c.collect_commands(a) assert "empty" in c.commands + a = TypeErrAddon() + c.collect_commands(a) + await tctx.master.await_log("Could not load") + def test_decorator(): with taddons.context() as tctx:
Can't run mitmproxy after adding a command without type annotations ##### Steps to reproduce the problem: 1. Open `mitmproxy/tools/console/consoleaddons.py` 2. Add arbitrary command without type annotations. For example: ``` @command.command("console.mycommand") def mycommand(self, flow): pass ``` 3. Try to run mitmproxy. Nothing happens. Absolutely. No exceptions, no UI. ##### Any other comments? What have you tried so far? If you add a command with type annotations ``` @command.command("console.mycommand") def mycommand(self, flow: flow.Flow) -> None: pass ``` everything will work ok. ##### System information Mitmproxy: 3.0.0.dev0004 (commit 68c32d8) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-104-generic-x86_64-with-Ubuntu-16.04-xenial
I will look into this ASAP This is causing the error https://github.com/mitmproxy/mitmproxy/blob/8dfb8a9a7471e00b0f723de66d3b63bd089e9802/mitmproxy/command.py#L34-L41 I need to look into why are we checking type annotations at runtime before proposing any solution :) So, the type annotations here are for dynamic command invocations. In the case of the return type, we ensure that the data returned from an addon's command matches the contract of the type annotations. This is a key part of ensuring safety in the command system, and making sure that everything remains composable without weird behaviour. We can go two ways here: either require a return type specification and give a proper error if it doesn't exist, or assume a return type of None. I lean (lightly) towards requiring an explicit annotation, since we absolutely require annotations on arguments. So I was thinking and came up with two solutions 1. Let this `NotImplementedError` stay and catch this [here](https://github.com/mitmproxy/mitmproxy/blob/eee109117f956600261bc938be52040d1474a97f/mitmproxy/command.py#L74) and throw `SyntaxError: missing type annotations in consoleaddons.py`. 2. Instead of `NotImplementedError`, use this `SyntaxError: missing type annotations in consoleaddons.py`,which might not be a pretty way
2018-05-11T22:45:23
mitmproxy/mitmproxy
3,117
mitmproxy__mitmproxy-3117
[ "2810" ]
2db0245233c272ad9edd0a7710396c38e7c3097d
diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py --- a/mitmproxy/addons/clientplayback.py +++ b/mitmproxy/addons/clientplayback.py @@ -59,9 +59,7 @@ def replay(self, f): # pragma: no cover # In all modes, we directly connect to the server displayed if self.options.mode.startswith("upstream:"): server_address = server_spec.parse_with_mode(self.options.mode)[1].address - server = connections.ServerConnection( - server_address, (self.options.listen_host, 0) - ) + server = connections.ServerConnection(server_address) server.connect() if r.scheme == "https": connect_request = http.make_connect_request((r.data.host, r.port)) @@ -85,10 +83,7 @@ def replay(self, f): # pragma: no cover r.first_line_format = "absolute" else: server_address = (r.host, r.port) - server = connections.ServerConnection( - server_address, - (self.options.listen_host, 0) - ) + server = connections.ServerConnection(server_address) server.connect() if r.scheme == "https": server.establish_tls( diff --git a/mitmproxy/command.py b/mitmproxy/command.py --- a/mitmproxy/command.py +++ b/mitmproxy/command.py @@ -236,7 +236,10 @@ def execute(self, cmdstr: str): """ Execute a command string. May raise CommandError. """ - parts = list(lexer(cmdstr)) + try: + parts = list(lexer(cmdstr)) + except ValueError as e: + raise exceptions.CommandError("Command error: %s" % e) if not len(parts) >= 1: raise exceptions.CommandError("Invalid command: %s" % cmdstr) return self.call_strings(parts[0], parts[1:]) diff --git a/mitmproxy/controller.py b/mitmproxy/controller.py --- a/mitmproxy/controller.py +++ b/mitmproxy/controller.py @@ -96,8 +96,8 @@ def take(self): def commit(self): """ Ultimately, messages are committed. This is done either automatically by - if the message is not taken or manually by the entity which called - .take(). + the handler if the message is not taken or manually by the entity which + called .take(). """ if self.state != "taken": raise exceptions.ControlException(
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 @@ -281,6 +281,8 @@ def test_simple(): c.execute("one.two too many args") with pytest.raises(exceptions.CommandError, match="Unknown"): c.call("nonexistent") + with pytest.raises(exceptions.CommandError, match="No escaped"): + c.execute("\\") c.add("empty", a.empty) c.execute("empty")
Mitmproxy crashes, when trying to use command, which contains '\' ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `:` 3. Input `\` and press `Enter`. I am seeing: ``` 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 308, 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_edit_text()) 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 218, in call parts = list(lexer(cmdstr)) File "/usr/lib/python3.5/shlex.py", line 263, in __next__ token = self.get_token() File "/usr/lib/python3.5/shlex.py", line 90, in get_token raw = self.read_token() File "/usr/lib/python3.5/shlex.py", line 185, in read_token raise ValueError("No escaped character") ValueError: No escaped character ``` ##### Any other comments? What have you tried so far? The exception is raised each time, when command line contains `\` (no matter where it is located.) ##### System information Mitmproxy: 3.0.0.dev64 (commit 6dd336f) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-109-generic-x86_64-with-Ubuntu-16.04-xenial
**Update:** Similar traceback appears, when we try to input `'` or `"` without closing quotation: ``` 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 309, 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 150, 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_edit_text()) 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 218, in call parts = list(lexer(cmdstr)) File "/usr/lib/python3.5/shlex.py", line 263, in __next__ token = self.get_token() File "/usr/lib/python3.5/shlex.py", line 90, in get_token raw = self.read_token() File "/usr/lib/python3.5/shlex.py", line 166, in read_token raise ValueError("No closing quotation") ValueError: No closing quotation ``` This is a problem with `shlex` as the exceptions suggest. I have looked into it and one solution for this would be to just catch `ValueError` exception raised, which is not a bad idea as we don't know where else it might fail. Another option is to check for the cases we know about and pass the string accordingly dealing with them to `shlex.shlex`( [Shlex Parsing rules](https://docs.python.org/2/library/shlex.html#parsing-rules)) along with catching the exception. @mhils @cortesi what would be the preferred way?
2018-05-12T01:43:06
mitmproxy/mitmproxy
3,119
mitmproxy__mitmproxy-3119
[ "2627" ]
a38497ac36aa72f0e431205d9c2b0394368d0810
diff --git a/examples/complex/websocket_inject_message.py b/examples/complex/websocket_inject_message.py new file mode 100644 --- /dev/null +++ b/examples/complex/websocket_inject_message.py @@ -0,0 +1,23 @@ +""" +This example shows how to inject a WebSocket message to the client. +Every new WebSocket connection will trigger a new asyncio task that +periodically injects a new message to the client. +""" +import asyncio +import mitmproxy.websocket + + +class InjectWebSocketMessage: + + async def inject(self, flow: mitmproxy.websocket.WebSocketFlow): + i = 0 + while not flow.ended and not flow.error: + await asyncio.sleep(5) + flow.inject_message(flow.client_conn, 'This is the #{} an injected message!'.format(i)) + i += 1 + + def websocket_start(self, flow): + asyncio.get_event_loop().create_task(self.inject(flow)) + + +addons = [InjectWebSocketMessage()] 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 @@ -1,3 +1,4 @@ +import queue import socket from OpenSSL import SSL @@ -165,8 +166,18 @@ def _handle_connection_closed(self, event, source_conn, other_conn, is_server): return False + def _inject_messages(self, endpoint, message_queue): + while True: + try: + payload = message_queue.get_nowait() + self.connections[endpoint].send_data(payload, final=True) + data = self.connections[endpoint].bytes_to_send() + endpoint.send(data) + except queue.Empty: + break + def __call__(self): - self.flow = WebSocketFlow(self.client_conn, self.server_conn, self.handshake_flow, self) + self.flow = WebSocketFlow(self.client_conn, self.server_conn, self.handshake_flow) self.flow.metadata['websocket_handshake'] = self.handshake_flow.id self.handshake_flow.metadata['websocket_flow'] = self.flow.id self.channel.ask("websocket_start", self.flow) @@ -176,6 +187,9 @@ def __call__(self): try: while not self.channel.should_exit.is_set(): + self._inject_messages(self.client_conn, self.flow._inject_messages_client) + self._inject_messages(self.server_conn, self.flow._inject_messages_server) + r = tcp.ssl_read_select(conns, 0.1) for conn in r: source_conn = self.client_conn if conn == self.client_conn.connection else self.server_conn @@ -198,4 +212,5 @@ def __call__(self): self.flow.error = flow.Error("WebSocket connection closed unexpectedly by {}: {}".format(s, repr(e))) self.channel.tell("websocket_error", self.flow) finally: + self.flow.ended = True self.channel.tell("websocket_end", self.flow) diff --git a/mitmproxy/websocket.py b/mitmproxy/websocket.py --- a/mitmproxy/websocket.py +++ b/mitmproxy/websocket.py @@ -1,4 +1,5 @@ import time +import queue from typing import List, Optional from wsproto.frame_protocol import CloseReason @@ -77,6 +78,11 @@ def __init__(self, client_conn, server_conn, handshake_flow, live=None): """True of this connection is streaming directly to the other endpoint.""" self.handshake_flow = handshake_flow """The HTTP flow containing the initial WebSocket handshake.""" + self.ended = False + """True when the WebSocket connection has been closed.""" + + self._inject_messages_client = queue.Queue(maxsize=1) + self._inject_messages_server = queue.Queue(maxsize=1) if handshake_flow: self.client_key = websockets.get_client_key(handshake_flow.request.headers) @@ -134,3 +140,25 @@ def message_info(self, message: WebSocketMessage) -> str: direction="->" if message.from_client else "<-", endpoint=self.handshake_flow.request.path, ) + + def inject_message(self, endpoint, payload): + """ + Inject and send a full WebSocket message to the remote endpoint. + This might corrupt your WebSocket connection! Be careful! + + The endpoint needs to be either flow.client_conn or flow.server_conn. + + If ``payload`` is of type ``bytes`` then the message is flagged as + being binary If it is of type ``str`` encoded as UTF-8 and sent as + text. + + :param payload: The message body to send. + :type payload: ``bytes`` or ``str`` + """ + + if endpoint == self.client_conn: + self._inject_messages_client.put(payload) + elif endpoint == self.server_conn: + self._inject_messages_server.put(payload) + else: + raise ValueError('Invalid endpoint')
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 @@ -467,3 +467,46 @@ def test_extension(self): assert self.master.state.flows[1].messages[3].type == websockets.OPCODE.BINARY assert self.master.state.flows[1].messages[4].content == b'\xde\xad\xbe\xef' assert self.master.state.flows[1].messages[4].type == websockets.OPCODE.BINARY + + +class TestInjectMessageClient(_WebSocketTest): + + @classmethod + def handle_websockets(cls, rfile, wfile): + pass + + def test_inject_message_client(self): + class Inject: + def websocket_start(self, flow): + flow.inject_message(flow.client_conn, 'This is an injected message!') + + self.proxy.set_addons(Inject()) + self.setup_connection() + + frame = websockets.Frame.from_file(self.client.rfile) + assert frame.header.opcode == websockets.OPCODE.TEXT + assert frame.payload == b'This is an injected message!' + + +class TestInjectMessageServer(_WebSocketTest): + + @classmethod + def handle_websockets(cls, rfile, wfile): + frame = websockets.Frame.from_file(rfile) + assert frame.header.opcode == websockets.OPCODE.TEXT + success = frame.payload == b'This is an injected message!' + + wfile.write(bytes(websockets.Frame(fin=1, opcode=websockets.OPCODE.TEXT, payload=str(success).encode()))) + wfile.flush() + + def test_inject_message_server(self): + class Inject: + def websocket_start(self, flow): + flow.inject_message(flow.server_conn, 'This is an injected message!') + + self.proxy.set_addons(Inject()) + self.setup_connection() + + frame = websockets.Frame.from_file(self.client.rfile) + assert frame.header.opcode == websockets.OPCODE.TEXT + assert frame.payload == b'True' 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 @@ -92,3 +92,15 @@ def test_message_kill(self): assert not f.messages[-1].killed f.messages[-1].kill() assert f.messages[-1].killed + + def test_inject_message(self): + f = tflow.twebsocketflow() + + with pytest.raises(ValueError): + f.inject_message(None, 'foobar') + + f.inject_message(f.client_conn, 'foobar') + assert f._inject_messages_client.qsize() == 1 + + f.inject_message(f.server_conn, 'foobar') + assert f._inject_messages_client.qsize() == 1
Allow to push/inject own WebSocket messages I inspect a HTTPS WebSocket traffic with Mitmproxy. Currently I can read/edit WS messages with: ```python ... class Intercept: def websocket_message(self, flow): print(flow.messages[-1]) ... def start(): return Intercept() ``` … as attached script to Mitmproxy. Please add a functionality to push/inject our own messages to the client/server. Not edit existing one, but send a new message.
Thanks for the feature request! Our current protocol stack makes this a bit difficult - but we are exploring a new approach which should make this much easier in the future. +1
2018-05-12T12:05:31
mitmproxy/mitmproxy
3,131
mitmproxy__mitmproxy-3131
[ "3134" ]
93b90a94ed0cb5cc309958e249c7dd652d64fef9
diff --git a/mitmproxy/version.py b/mitmproxy/version.py --- a/mitmproxy/version.py +++ b/mitmproxy/version.py @@ -3,7 +3,7 @@ # The actual version string. For precompiled binaries, this will be changed to include the build # tag, e.g. "3.0.0.dev0042-0xcafeabc" -VERSION = "4.0.0" +VERSION = "5.0.0" PATHOD = "pathod " + VERSION MITMPROXY = "mitmproxy " + VERSION diff --git a/release/ci.py b/release/ci.py --- a/release/ci.py +++ b/release/ci.py @@ -1,5 +1,7 @@ #!/usr/bin/env python3 +import glob +import re import contextlib import os import platform @@ -10,7 +12,6 @@ import zipfile from os.path import join, abspath, dirname, exists, basename -import cryptography.fernet import click # https://virtualenv.pypa.io/en/latest/userguide.html#windows-notes @@ -73,17 +74,17 @@ def Archive(name): TAG = os.environ.get("TRAVIS_TAG", os.environ.get("APPVEYOR_REPO_TAG_NAME", None)) BRANCH = os.environ.get("TRAVIS_BRANCH", os.environ.get("APPVEYOR_REPO_BRANCH", None)) if TAG: - VERSION = TAG + VERSION = re.sub('^v', '', TAG) UPLOAD_DIR = VERSION elif BRANCH: - VERSION = BRANCH + VERSION = re.sub('^v', '', BRANCH) UPLOAD_DIR = "branches/%s" % VERSION else: print("Could not establish build name - exiting." % BRANCH) sys.exit(0) - print("BUILD VERSION=%s" % VERSION) +print("BUILD UPLOAD_DIR=%s" % UPLOAD_DIR) def archive_name(bdist: str) -> str: @@ -99,23 +100,6 @@ def archive_name(bdist: str) -> str: ) -def wheel_name() -> str: - return "mitmproxy-{version}-py3-none-any.whl".format(version=VERSION) - - -def installer_name() -> str: - ext = { - "Windows": "exe", - "Darwin": "dmg", - "Linux": "run" - }[platform.system()] - return "mitmproxy-{version}-{platform}-installer.{ext}".format( - version=VERSION, - platform=PLATFORM_TAG, - ext=ext, - ) - - @contextlib.contextmanager def chdir(path: str): old_dir = os.getcwd() @@ -134,7 +118,7 @@ def cli(): @cli.command("info") def info(): - print("Version: %s" % VERSION) + click.echo("Version: %s" % VERSION) @cli.command("build") @@ -142,23 +126,41 @@ def build(): """ Build a binary distribution """ + os.makedirs(DIST_DIR, exist_ok=True) + if "WHEEL" in os.environ: + build_wheel() + else: + click.echo("Not building wheels.") + build_pyinstaller() + + +def build_wheel(): + click.echo("Building wheel...") + subprocess.check_call([ + "python", + "setup.py", + "-q", + "bdist_wheel", + "--dist-dir", DIST_DIR, + ]) + + whl = glob.glob(join(DIST_DIR, 'mitmproxy-*-py3-none-any.whl'))[0] + click.echo("Found wheel package: {}".format(whl)) + + subprocess.check_call([ + "tox", + "-e", "wheeltest", + "--", + whl + ]) + + +def build_pyinstaller(): if exists(PYINSTALLER_TEMP): shutil.rmtree(PYINSTALLER_TEMP) if exists(PYINSTALLER_DIST): shutil.rmtree(PYINSTALLER_DIST) - os.makedirs(DIST_DIR, exist_ok=True) - - if "WHEEL" in os.environ: - print("Building wheel...") - subprocess.check_call( - [ - "python", - "setup.py", "-q", "bdist_wheel", - "--dist-dir", "release/dist", - ] - ) - for bdist, tools in sorted(BDISTS.items()): with Archive(join(DIST_DIR, archive_name(bdist))) as archive: for tool in tools: @@ -168,7 +170,7 @@ def build(): # This is PyInstaller, so it messes up paths. # We need to make sure that we are in the spec folder. with chdir(PYINSTALLER_SPEC): - print("Building %s binary..." % tool) + click.echo("Building %s binary..." % tool) excludes = [] if tool != "mitmweb": excludes.append("mitmproxy.tools.web") @@ -209,11 +211,11 @@ def build(): ) executable = executable.replace("_main", "") - print("> %s --version" % executable) - print(subprocess.check_output([executable, "--version"]).decode()) + click.echo("> %s --version" % executable) + click.echo(subprocess.check_output([executable, "--version"]).decode()) archive.add(executable, basename(executable)) - print("Packed {}.".format(archive_name(bdist))) + click.echo("Packed {}.".format(archive_name(bdist))) def is_pr(): @@ -229,34 +231,40 @@ def is_pr(): @cli.command("upload") def upload(): """ - Upload snapshot to snapshot server + Upload build artifacts to snapshot server and + upload wheel package to PyPi """ # This requires some explanation. The AWS access keys are only exposed to # privileged builds - that is, they are not available to PRs from forks. # However, they ARE exposed to PRs from a branch within the main repo. This # check catches that corner case, and prevents an inadvertent upload. if is_pr(): - print("Refusing to upload a pull request") + click.echo("Refusing to upload a pull request") return + if "AWS_ACCESS_KEY_ID" in os.environ: - subprocess.check_call( - [ - "aws", "s3", "cp", - "--acl", "public-read", - DIST_DIR + "/", - "s3://snapshots.mitmproxy.org/%s/" % UPLOAD_DIR, - "--recursive", - ] - ) - - [email protected]("decrypt") [email protected]('infile', type=click.File('rb')) [email protected]('outfile', type=click.File('wb')) [email protected]('key', envvar='RTOOL_KEY') -def decrypt(infile, outfile, key): - f = cryptography.fernet.Fernet(key.encode()) - outfile.write(f.decrypt(infile.read())) + subprocess.check_call([ + "aws", "s3", "cp", + "--acl", "public-read", + DIST_DIR + "/", + "s3://snapshots.mitmproxy.org/%s/" % UPLOAD_DIR, + "--recursive", + ]) + + upload_pypi = ( + TAG and + "WHEEL" in os.environ and + "TWINE_USERNAME" in os.environ and + "TWINE_PASSWORD" in os.environ + ) + if upload_pypi: + filename = "mitmproxy-{version}-py3-none-any.whl".format(version=VERSION) + click.echo("Uploading {} to PyPi...".format(filename)) + subprocess.check_call([ + "twine", + "upload", + join(DIST_DIR, filename) + ]) if __name__ == "__main__": diff --git a/release/rtool.py b/release/rtool.py deleted file mode 100755 --- a/release/rtool.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python3 - -import contextlib -import os -import sys -import platform -import runpy -import shlex -import subprocess -from os.path import join, abspath, dirname - -import cryptography.fernet -import click - - -ROOT_DIR = abspath(join(dirname(__file__), "..")) -RELEASE_DIR = join(ROOT_DIR, "release") -DIST_DIR = join(RELEASE_DIR, "dist") -VERSION_FILE = join(ROOT_DIR, "mitmproxy", "version.py") - - -def git(args: str) -> str: - with chdir(ROOT_DIR): - return subprocess.check_output(["git"] + shlex.split(args)).decode() - - -def get_version(dev: bool = False, build: bool = False) -> str: - x = runpy.run_path(VERSION_FILE) - return x["get_version"](dev, build, True) - - -def wheel_name() -> str: - return "mitmproxy-{version}-py3-none-any.whl".format( - version=get_version(True), - ) - - [email protected] -def chdir(path: str): - old_dir = os.getcwd() - os.chdir(path) - yield - os.chdir(old_dir) - - [email protected](chain=True) -def cli(): - """ - mitmproxy build tool - """ - pass - - [email protected]("contributors") -def contributors(): - """ - Update CONTRIBUTORS.md - """ - with chdir(ROOT_DIR): - print("Updating CONTRIBUTORS...") - contributors_data = git("shortlog -n -s") - with open("CONTRIBUTORS", "wb") as f: - f.write(contributors_data.encode()) - - [email protected]("upload-release") [email protected]('--username', prompt=True) [email protected]_option(confirmation_prompt=False) [email protected]('--repository', default="pypi") -def upload_release(username, password, repository): - """ - Upload wheels to PyPI - """ - filename = wheel_name() - print("Uploading {} to {}...".format(filename, repository)) - subprocess.check_call([ - "twine", - "upload", - "-u", username, - "-p", password, - "-r", repository, - join(DIST_DIR, filename) - ]) - - [email protected]("homebrew-pr") -def homebrew_pr(): - """ - Create a new Homebrew PR - """ - if platform.system() != "Darwin": - print("You need to run this on macOS to create a new Homebrew PR. Sorry.") - sys.exit(1) - - print("Creating a new PR with Homebrew...") - subprocess.check_call([ - "brew", - "bump-formula-pr", - "--url", "https://github.com/mitmproxy/mitmproxy/archive/v{}".format(get_version()), - "mitmproxy", - ]) - - [email protected]("encrypt") [email protected]('infile', type=click.File('rb')) [email protected]('outfile', type=click.File('wb')) [email protected]('key', envvar='RTOOL_KEY') -def encrypt(infile, outfile, key): - f = cryptography.fernet.Fernet(key.encode()) - outfile.write(f.encrypt(infile.read())) - - -if __name__ == "__main__": - cli()
Release filenames are inconsistent ##### Steps to reproduce the problem: 1. Roll a new release 2. Some releases have a "v4.0.0" version spec, others have a "4.0.0" version spec: https://snapshots.mitmproxy.org/v4.0.1/ 3. v4.0.0 is unexpected and breaks the Linux download link on mitmproxy.org.
2018-05-17T01:15:44
mitmproxy/mitmproxy
3,157
mitmproxy__mitmproxy-3157
[ "3147" ]
76c056affdad6a8f57a523534c56a50524c8f7e9
diff --git a/mitmproxy/optmanager.py b/mitmproxy/optmanager.py --- a/mitmproxy/optmanager.py +++ b/mitmproxy/optmanager.py @@ -107,6 +107,7 @@ def add_option( choices: typing.Optional[typing.Sequence[str]] = None ) -> None: self._options[name] = _Option(name, typespec, default, help, choices) + self.changed.send(self, updated={name}) @contextlib.contextmanager def rollback(self, updated, reraise=False): diff --git a/mitmproxy/tools/console/options.py b/mitmproxy/tools/console/options.py --- a/mitmproxy/tools/console/options.py +++ b/mitmproxy/tools/console/options.py @@ -106,6 +106,8 @@ def __init__(self, master): self.master.options.changed.connect(self.sig_mod) def sig_mod(self, *args, **kwargs): + self.opts = sorted(self.master.options.keys()) + self.maxlen = max(len(i) for i in self.opts) self._modified() self.set_focus(self.index)
mitmproxy - custom addon options not visible ##### Steps to reproduce the problem: 1. Start the following addon with `mitmproxy --scripts eg.py` ```python from mitmproxy import http, ctx class MyAddon: def load(self, loader) -> None: loader.add_option(name='AAAAA_addon_message', typespec=str, default='your request is bad and you should feel bad', help='Respond with this message') loader.add_option(name='AAAAA_addon_status_code', typespec=int, default=400, help='Respond with this status code') def request(self, flow: http.HTTPFlow) -> None: ctx.log.info('my_addon request') def response(self, flow: http.HTTPFlow) -> None: ctx.log.info('my_addon response') flow.response.status_code = ctx.options.AAAAA_status_code flow.response.content = ctx.options.AAAAA_addon_message.encode('utf-8') addons = [ MyAddon() ] ``` 2. Open the options with 'O' key binding and see the options AAAA_* are not editable <img width="418" alt="screen shot 2018-05-22 at 3 05 02 pm" src="https://user-images.githubusercontent.com/222833/40343185-f92caa5c-5dd1-11e8-9449-8facc05c16f6.png"> ##### Any other comments? What have you tried so far? mitmweb displays the options correctly: <img width="896" alt="screen shot 2018-05-22 at 3 05 32 pm" src="https://user-images.githubusercontent.com/222833/40343148-d00229fe-5dd1-11e8-94d0-0cd352fe870c.png"> Could be related to the [deferred options](https://github.com/mitmproxy/mitmproxy/commit/f7d7e31f06dadcf0f7801ab1db055f8609c88a71)? This affects the current version `4.0.1` as well as `master`. ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ``` (venv) ➜ mitmproxy git:(master) ✗ mitmproxy --version Mitmproxy: 5.0.0.dev12 (commit 7aaf495) Python: 3.6.5 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Darwin-17.5.0-x86_64-i386-64bit ``` <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Thanks for providing super easy steps to reproduce this! :smiley:
2018-05-25T01:41:23
mitmproxy/mitmproxy
3,163
mitmproxy__mitmproxy-3163
[ "3162" ]
d1e3968fa887f601339ac158e4c0f5fff4b18a49
diff --git a/mitmproxy/optmanager.py b/mitmproxy/optmanager.py --- a/mitmproxy/optmanager.py +++ b/mitmproxy/optmanager.py @@ -91,7 +91,7 @@ class OptManager: mutation doesn't change the option state inadvertently. """ def __init__(self): - self._deferred: typing.Dict[str, str] = {} + self.deferred: typing.Dict[str, str] = {} self.changed = blinker.Signal() self.errored = blinker.Signal() # Options must be the last attribute here - after that, we raise an @@ -217,6 +217,10 @@ def update_known(self, **kwargs): self.changed.send(self, updated=updated) return unknown + def update_defer(self, **kwargs): + unknown = self.update_known(**kwargs) + self.deferred.update(unknown) + def update(self, **kwargs): u = self.update_known(**kwargs) if u: @@ -303,7 +307,7 @@ def set(self, *spec, defer=False): else: unknown[optname] = optval if defer: - self._deferred.update(unknown) + self.deferred.update(unknown) elif unknown: raise exceptions.OptionsError("Unknown options: %s" % ", ".join(unknown.keys())) self.update(**vals) @@ -314,12 +318,12 @@ def process_deferred(self): have since been added. """ update = {} - for optname, optval in self._deferred.items(): + for optname, optval in self.deferred.items(): if optname in self._options: update[optname] = self.parse_setval(self._options[optname], optval) self.update(**update) for k in update.keys(): - del self._deferred[k] + del self.deferred[k] def parse_setval(self, o: _Option, optstr: typing.Optional[str]) -> typing.Any: """ @@ -494,26 +498,21 @@ def parse(text): return data -def load(opts, text): +def load(opts: OptManager, text: str) -> None: """ Load configuration from text, over-writing options already set in this object. May raise OptionsError if the config file is invalid. - - Returns a dictionary of all unknown options. """ data = parse(text) - return opts.update_known(**data) + opts.update_defer(**data) -def load_paths(opts, *paths): +def load_paths(opts: OptManager, *paths: str) -> None: """ Load paths in order. Each path takes precedence over the previous path. Paths that don't exist are ignored, errors raise an OptionsError. - - Returns a dictionary of unknown options. """ - ret = {} for p in paths: p = os.path.expanduser(p) if os.path.exists(p) and os.path.isfile(p): @@ -525,15 +524,14 @@ def load_paths(opts, *paths): "Error reading %s: %s" % (p, e) ) try: - ret.update(load(opts, txt)) + load(opts, txt) except exceptions.OptionsError as e: raise exceptions.OptionsError( "Error reading %s: %s" % (p, e) ) - return ret -def serialize(opts, text, defaults=False): +def serialize(opts: OptManager, text: str, defaults: bool = False) -> str: """ Performs a round-trip serialization. If text is not None, it is treated as a previous serialization that should be modified @@ -554,7 +552,7 @@ def serialize(opts, text, defaults=False): return ruamel.yaml.round_trip_dump(data) -def save(opts, path, defaults=False): +def save(opts: OptManager, path: str, defaults: bool =False) -> None: """ Save to path. If the destination file exists, modify it in-place. diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -93,7 +93,7 @@ def run( sys.exit(1) try: opts.confdir = args.confdir - unknown = optmanager.load_paths( + optmanager.load_paths( opts, os.path.join(opts.confdir, OPTIONS_FILE_NAME), ) @@ -109,7 +109,6 @@ def run( server = proxy.server.DummyServer(pconf) master.server = server - opts.update_known(**unknown) if args.options: print(optmanager.dump_defaults(opts)) sys.exit(0)
diff --git a/test/mitmproxy/test_optmanager.py b/test/mitmproxy/test_optmanager.py --- a/test/mitmproxy/test_optmanager.py +++ b/test/mitmproxy/test_optmanager.py @@ -269,11 +269,13 @@ def test_serialize(): t = "# a comment" optmanager.load(o2, t) - assert optmanager.load(o2, "foobar: '123'") == {"foobar": "123"} + optmanager.load(o2, "foobar: '123'") + assert o2.deferred == {"foobar": "123"} t = "" optmanager.load(o2, t) - assert optmanager.load(o2, "foobar: '123'") == {"foobar": "123"} + optmanager.load(o2, "foobar: '123'") + assert o2.deferred == {"foobar": "123"} def test_serialize_defaults(): @@ -297,7 +299,8 @@ def test_saving(tmpdir): with open(dst, 'a') as f: f.write("foobar: '123'") - assert optmanager.load_paths(o, dst) == {"foobar": "123"} + optmanager.load_paths(o, dst) + assert o.deferred == {"foobar": "123"} with open(dst, 'a') as f: f.write("'''") @@ -426,13 +429,13 @@ def test_set(): assert opts.seqstr == [] with pytest.raises(exceptions.OptionsError): - opts.set("deferred=wobble") + opts.set("deferredoption=wobble") - opts.set("deferred=wobble", defer=True) - assert "deferred" in opts._deferred + opts.set("deferredoption=wobble", defer=True) + assert "deferredoption" in opts.deferred opts.process_deferred() - assert "deferred" in opts._deferred - opts.add_option("deferred", str, "default", "help") + assert "deferredoption" in opts.deferred + opts.add_option("deferredoption", str, "default", "help") opts.process_deferred() - assert "deferred" not in opts._deferred - assert opts.deferred == "wobble" + assert "deferredoption" not in opts.deferred + assert opts.deferredoption == "wobble"
Addon defined options set in config.yaml not used *New to this, so apologies if I'm just missing something obvious.* ##### Steps to reproduce the problem: 1. Define test.py addon ```py from mitmproxy import ctx class OptionsTest: def load(self, loader): loader.add_option( name = "anoption", typespec = str, default = "None", help = "Add a header to responses", ) def configure(self, updates): ctx.log.info('Test option: %s' % ctx.options.anoption) def response(self, flow): flow.response.headers["anoption"] = str(ctx.options.anoption) addons = [ OptionsTest() ] ``` 2. Load addon and define `anoption` in `~/.mitmproxy/config.yaml` ```yaml scripts: - ~/.mitmproxy/test.py anoption: "foo" ``` 3. Notice that `anoption` isn't documented in output from `mitmweb --options` 4. Run `mitmdump` and note that the log shows the option's default value, not the one defined in `config.yaml` ```bash mitmdump Loading script ~/.mitmproxy/test.py Test option: None Proxy server listening at http://*:8080 ``` ##### Any other comments? What have you tried so far? Options set on the command line are loaded: ```bash mitmdump --set anoption="bar" Loading script ~/.mitmproxy/test.py Test option: bar Proxy server listening at http://*:8080 ``` ##### System information ```bash mitmproxy --version Mitmproxy: 4.0.1 Python: 3.6.5 OpenSSL: OpenSSL 1.0.2o 27 Mar 2018 Platform: Darwin-17.5.0-x86_64-i386-64bit ``` <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
2018-05-26T22:13:47
mitmproxy/mitmproxy
3,164
mitmproxy__mitmproxy-3164
[ "3160" ]
d1e3968fa887f601339ac158e4c0f5fff4b18a49
diff --git a/mitmproxy/addons/block.py b/mitmproxy/addons/block.py --- a/mitmproxy/addons/block.py +++ b/mitmproxy/addons/block.py @@ -21,17 +21,19 @@ def load(self, loader): ) def clientconnect(self, layer): - address = ipaddress.ip_address(layer.client_conn.address[0]) + astr = layer.client_conn.address[0] + + parts = astr.rsplit("%", 1) + address = ipaddress.ip_address(parts[0]) if isinstance(address, ipaddress.IPv6Address): address = address.ipv4_mapped or address - ipa = ipaddress.ip_address(address) - if ipa.is_loopback: + if address.is_loopback: return - if ctx.options.block_private and ipa.is_private: - ctx.log.warn("Client connection from %s killed by block_private" % address) + if ctx.options.block_private and address.is_private: + ctx.log.warn("Client connection from %s killed by block_private" % astr) layer.reply.kill() - if ctx.options.block_global and ipa.is_global: - ctx.log.warn("Client connection from %s killed by block_global" % address) + if ctx.options.block_global and address.is_global: + ctx.log.warn("Client connection from %s killed by block_global" % astr) layer.reply.kill() \ No newline at end of file diff --git a/mitmproxy/optmanager.py b/mitmproxy/optmanager.py --- a/mitmproxy/optmanager.py +++ b/mitmproxy/optmanager.py @@ -91,7 +91,7 @@ class OptManager: mutation doesn't change the option state inadvertently. """ def __init__(self): - self._deferred: typing.Dict[str, str] = {} + self.deferred: typing.Dict[str, str] = {} self.changed = blinker.Signal() self.errored = blinker.Signal() # Options must be the last attribute here - after that, we raise an @@ -217,6 +217,10 @@ def update_known(self, **kwargs): self.changed.send(self, updated=updated) return unknown + def update_defer(self, **kwargs): + unknown = self.update_known(**kwargs) + self.deferred.update(unknown) + def update(self, **kwargs): u = self.update_known(**kwargs) if u: @@ -303,7 +307,7 @@ def set(self, *spec, defer=False): else: unknown[optname] = optval if defer: - self._deferred.update(unknown) + self.deferred.update(unknown) elif unknown: raise exceptions.OptionsError("Unknown options: %s" % ", ".join(unknown.keys())) self.update(**vals) @@ -314,12 +318,12 @@ def process_deferred(self): have since been added. """ update = {} - for optname, optval in self._deferred.items(): + for optname, optval in self.deferred.items(): if optname in self._options: update[optname] = self.parse_setval(self._options[optname], optval) self.update(**update) for k in update.keys(): - del self._deferred[k] + del self.deferred[k] def parse_setval(self, o: _Option, optstr: typing.Optional[str]) -> typing.Any: """ @@ -494,26 +498,21 @@ def parse(text): return data -def load(opts, text): +def load(opts: OptManager, text: str) -> None: """ Load configuration from text, over-writing options already set in this object. May raise OptionsError if the config file is invalid. - - Returns a dictionary of all unknown options. """ data = parse(text) - return opts.update_known(**data) + opts.update_defer(**data) -def load_paths(opts, *paths): +def load_paths(opts: OptManager, *paths: str) -> None: """ Load paths in order. Each path takes precedence over the previous path. Paths that don't exist are ignored, errors raise an OptionsError. - - Returns a dictionary of unknown options. """ - ret = {} for p in paths: p = os.path.expanduser(p) if os.path.exists(p) and os.path.isfile(p): @@ -525,15 +524,14 @@ def load_paths(opts, *paths): "Error reading %s: %s" % (p, e) ) try: - ret.update(load(opts, txt)) + load(opts, txt) except exceptions.OptionsError as e: raise exceptions.OptionsError( "Error reading %s: %s" % (p, e) ) - return ret -def serialize(opts, text, defaults=False): +def serialize(opts: OptManager, text: str, defaults: bool = False) -> str: """ Performs a round-trip serialization. If text is not None, it is treated as a previous serialization that should be modified @@ -554,7 +552,7 @@ def serialize(opts, text, defaults=False): return ruamel.yaml.round_trip_dump(data) -def save(opts, path, defaults=False): +def save(opts: OptManager, path: str, defaults: bool =False) -> None: """ Save to path. If the destination file exists, modify it in-place. diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -93,7 +93,7 @@ def run( sys.exit(1) try: opts.confdir = args.confdir - unknown = optmanager.load_paths( + optmanager.load_paths( opts, os.path.join(opts.confdir, OPTIONS_FILE_NAME), ) @@ -109,7 +109,6 @@ def run( server = proxy.server.DummyServer(pconf) master.server = server - opts.update_known(**unknown) if args.options: print(optmanager.dump_defaults(opts)) sys.exit(0)
diff --git a/test/mitmproxy/addons/test_block.py b/test/mitmproxy/addons/test_block.py --- a/test/mitmproxy/addons/test_block.py +++ b/test/mitmproxy/addons/test_block.py @@ -17,6 +17,7 @@ (True, False, False, ("::ffff:172.20.0.1",)), (True, False, False, ("::ffff:192.168.1.1",)), (True, False, False, ("fe80::",)), + (True, False, False, (r"::ffff:192.168.1.1%scope",)), # block_global: global (True, False, True, ("1.1.1.1",)), (True, False, True, ("8.8.8.8",)), @@ -25,6 +26,7 @@ (True, False, True, ("::ffff:8.8.8.8",)), (True, False, True, ("::ffff:216.58.207.174",)), (True, False, True, ("2001:4860:4860::8888",)), + (True, False, True, (r"2001:4860:4860::8888%scope",)), # block_private: loopback @@ -37,6 +39,7 @@ (False, True, True, ("::ffff:10.0.0.1",)), (False, True, True, ("::ffff:172.20.0.1",)), (False, True, True, ("::ffff:192.168.1.1",)), + (False, True, True, (r"::ffff:192.168.1.1%scope",)), (False, True, True, ("fe80::",)), # block_private: global (False, True, False, ("1.1.1.1",)), @@ -45,6 +48,7 @@ (False, True, False, ("::ffff:1.1.1.1",)), (False, True, False, ("::ffff:8.8.8.8",)), (False, True, False, ("::ffff:216.58.207.174",)), + (False, True, False, (r"::ffff:216.58.207.174%scope",)), (False, True, False, ("2001:4860:4860::8888",)), ]) @pytest.mark.asyncio diff --git a/test/mitmproxy/test_optmanager.py b/test/mitmproxy/test_optmanager.py --- a/test/mitmproxy/test_optmanager.py +++ b/test/mitmproxy/test_optmanager.py @@ -269,11 +269,13 @@ def test_serialize(): t = "# a comment" optmanager.load(o2, t) - assert optmanager.load(o2, "foobar: '123'") == {"foobar": "123"} + optmanager.load(o2, "foobar: '123'") + assert o2.deferred == {"foobar": "123"} t = "" optmanager.load(o2, t) - assert optmanager.load(o2, "foobar: '123'") == {"foobar": "123"} + optmanager.load(o2, "foobar: '123'") + assert o2.deferred == {"foobar": "123"} def test_serialize_defaults(): @@ -297,7 +299,8 @@ def test_saving(tmpdir): with open(dst, 'a') as f: f.write("foobar: '123'") - assert optmanager.load_paths(o, dst) == {"foobar": "123"} + optmanager.load_paths(o, dst) + assert o.deferred == {"foobar": "123"} with open(dst, 'a') as f: f.write("'''") @@ -426,13 +429,13 @@ def test_set(): assert opts.seqstr == [] with pytest.raises(exceptions.OptionsError): - opts.set("deferred=wobble") + opts.set("deferredoption=wobble") - opts.set("deferred=wobble", defer=True) - assert "deferred" in opts._deferred + opts.set("deferredoption=wobble", defer=True) + assert "deferredoption" in opts.deferred opts.process_deferred() - assert "deferred" in opts._deferred - opts.add_option("deferred", str, "default", "help") + assert "deferredoption" in opts.deferred + opts.add_option("deferredoption", str, "default", "help") opts.process_deferred() - assert "deferred" not in opts._deferred - assert opts.deferred == "wobble" + assert "deferredoption" not in opts.deferred + assert opts.deferredoption == "wobble"
Bridge Addresses Causing "block.py" Add-on to Fail with `ValueError` ##### Steps to reproduce the problem: 1. create an ipv6 network connection to the proxy host on a bridge 2. set the device to request through the proxy host 3. watch some traffic start flowing ``` Addon error: Traceback (most recent call last): File "/usr/local/Cellar/mitmproxy/4.0.1/libexec/lib/python3.6/site-packages/mitmproxy/addons/block.py", line 24, in clientconnect address = ipaddress.ip_address(layer.client_conn.address[0]) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ipaddress.py", line 54, in ip_address address) ValueError: 'fe80::884:9f3b:3afd:6eae%bridge100' does not appear to be an IPv4 or IPv6 address ``` ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ``` $ mitmproxy --version Mitmproxy: 4.0.1 Python: 3.6.5 OpenSSL: OpenSSL 1.0.2o 27 Mar 2018 Platform: Darwin-17.6.0-x86_64-i386-64bit ```
2018-05-26T22:53:20
mitmproxy/mitmproxy
3,172
mitmproxy__mitmproxy-3172
[ "3133" ]
3ccc319a27fcd08517127880d498f74380c60d3d
diff --git a/mitmproxy/master.py b/mitmproxy/master.py --- a/mitmproxy/master.py +++ b/mitmproxy/master.py @@ -119,7 +119,15 @@ def shutdown(self): """ if not self.should_exit.is_set(): self.should_exit.set() - asyncio.run_coroutine_threadsafe(self._shutdown(), loop = self.channel.loop) + ret = asyncio.run_coroutine_threadsafe(self._shutdown(), loop=self.channel.loop) + # Weird band-aid to make sure that self._shutdown() is actually executed, + # which otherwise hangs the process as the proxy server is threaded. + # This all needs to be simplified when the proxy server runs on asyncio as well. + if not self.channel.loop.is_running(): # pragma: no cover + try: + self.channel.loop.run_until_complete(asyncio.wrap_future(ret)) + except RuntimeError: + pass # Event loop stopped before Future completed. def _change_reverse_host(self, f): """ diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -119,9 +119,6 @@ def run( if extra: opts.update(**extra(args)) - def cleankill(*args, **kwargs): - master.shutdown() - signal.signal(signal.SIGTERM, cleankill) loop = asyncio.get_event_loop() for signame in ('SIGINT', 'SIGTERM'): try: @@ -129,6 +126,15 @@ def cleankill(*args, **kwargs): except NotImplementedError: # Not supported on Windows pass + + # Make sure that we catch KeyboardInterrupts on Windows. + # https://stackoverflow.com/a/36925722/934719 + if os.name == "nt": + async def wakeup(): + while True: + await asyncio.sleep(0.2) + asyncio.ensure_future(wakeup()) + master.run() except exceptions.OptionsError as e: print("%s: %s" % (sys.argv[0], e), file=sys.stderr)
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 @@ -787,7 +787,7 @@ async def test_unnecessary_serverconnect(self): """A replayed/fake response with no upstream_cert should not connect to an upstream server""" self.set_addons(AFakeResponse()) assert self.pathod("200").status_code == 200 - asyncio.sleep(0.1) + await asyncio.sleep(0.1) assert not self.proxy.tmaster.has_log("serverconnect")
mitmweb can't be closed by Ctrl+C on Windows anymore ##### Steps to reproduce the problem: I even compared this behavior with 3.0.4. **4.0.1:** 1. Run `mitmweb` 2. Press Ctrl+C in console 3. Nothing happens. 4. if you close web browser, you will get a warning: 5. >`lib\asyncio\base_events.py:492`: RuntimeWarning: coroutine 'Master._shutdown' was never awaited self._ready.clear() 6. So, you have to kill `python.exe` manually. **3.0.4:** 1. Run `mitmweb` 2. Press Ctrl+C in console 3. `mitmweb` will be closed regardless of a browser. ##### Any other comments? What have you tried so far? 4.0.1 works fine on **Linux**. It may be connected with `asyncio`. And just a guess: https://gist.github.com/lambdalisue/05d5654bd1ec04992ad316d50924137c (Ctrl+C hotfix patch of asyncio on Windows) ##### System information > Mitmproxy: 4.0.1 Python: 3.6.2 (3.6.5 - the same issue) OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Windows-7-6.1.7601-SP1
Thanks - most likely that's it. Do you want to send a quick PR? Sorry, I doubt so. I have no idea where are `mitmweb`'s sources in this repository and where to insert that fix. This also happens with `mitmdump` and the problem was introduced in this commit: https://github.com/mitmproxy/mitmproxy/commit/44016a0de519469792769f7b78c37e7de9bfde24 ``` 44016a0de519469792769f7b78c37e7de9bfde24 is the first bad commit commit 44016a0de519469792769f7b78c37e7de9bfde24 Author: Aldo Cortesi <[email protected]> Date: Sat Apr 7 11:46:34 2018 +1200 asyncio: shift script reloading out of the tick event The tick event is a nasty compromise, left over from when we didn't have an event loop. This is the first patch in a series that explores moving our built-in addons to managing coroutines on the eventloop directly for periodic tasks. ``` I tried having a go at fixing this but unfortunately I don't know enough about asyncio.
2018-05-28T13:22:21
mitmproxy/mitmproxy
3,174
mitmproxy__mitmproxy-3174
[ "3080" ]
3ccc319a27fcd08517127880d498f74380c60d3d
diff --git a/mitmproxy/platform/windows.py b/mitmproxy/platform/windows.py --- a/mitmproxy/platform/windows.py +++ b/mitmproxy/platform/windows.py @@ -1,25 +1,44 @@ -import collections +import contextlib import ctypes import ctypes.wintypes +import io +import json import os +import re import socket -import struct +import socketserver import threading import time +import typing -import argparse +import click +import collections import pydivert import pydivert.consts -import pickle -import socketserver -PROXY_API_PORT = 8085 +REDIRECT_API_HOST = "127.0.0.1" +REDIRECT_API_PORT = 8085 + + +########################## +# Resolver + +def read(rfile: io.BufferedReader) -> typing.Any: + x = rfile.readline().strip() + return json.loads(x) + + +def write(data, wfile: io.BufferedWriter) -> None: + wfile.write(json.dumps(data).encode() + b"\n") + wfile.flush() class Resolver: + sock: socket.socket + lock: threading.RLock def __init__(self): - self.socket = None + self.sock = None self.lock = threading.RLock() def setup(self): @@ -28,406 +47,528 @@ def setup(self): self._connect() def _connect(self): - if self.socket: - self.socket.close() - self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.socket.connect(("127.0.0.1", PROXY_API_PORT)) - - self.wfile = self.socket.makefile('wb') - self.rfile = self.socket.makefile('rb') - pickle.dump(os.getpid(), self.wfile) - - def original_addr(self, csock): - client = csock.getpeername()[:2] + if self.sock: + self.sock.close() + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.connect((REDIRECT_API_HOST, REDIRECT_API_PORT)) + + self.wfile = self.sock.makefile('wb') + self.rfile = self.sock.makefile('rb') + write(os.getpid(), self.wfile) + + def original_addr(self, csock: socket.socket): + ip, port = csock.getpeername()[:2] + ip = re.sub("^::ffff:(?=\d+.\d+.\d+.\d+$)", "", ip) + ip = ip.split("%", 1)[0] with self.lock: try: - pickle.dump(client, self.wfile) - self.wfile.flush() - addr = pickle.load(self.rfile) + write((ip, port), self.wfile) + addr = read(self.rfile) if addr is None: raise RuntimeError("Cannot resolve original destination.") - addr = list(addr) - addr[0] = str(addr[0]) - addr = tuple(addr) - return addr + return tuple(addr) except (EOFError, socket.error): self._connect() return self.original_addr(csock) class APIRequestHandler(socketserver.StreamRequestHandler): - """ TransparentProxy API: Returns the pickled server address, port tuple for each received pickled client address, port tuple. """ def handle(self): - proxifier = self.server.proxifier - pid = None + proxifier: TransparentProxy = self.server.proxifier try: - pid = pickle.load(self.rfile) - if pid is not None: - proxifier.trusted_pids.add(pid) - - while True: - client = pickle.load(self.rfile) - server = proxifier.client_server_map.get(client, None) - pickle.dump(server, self.wfile) - self.wfile.flush() - + pid: int = read(self.rfile) + with proxifier.exempt(pid): + while True: + client = tuple(read(self.rfile)) + try: + server = proxifier.client_server_map[client] + except KeyError: + server = None + write(server, self.wfile) except (EOFError, socket.error): - proxifier.trusted_pids.discard(pid) + pass class APIServer(socketserver.ThreadingMixIn, socketserver.TCPServer): def __init__(self, proxifier, *args, **kwargs): - socketserver.TCPServer.__init__(self, *args, **kwargs) + super().__init__(*args, **kwargs) self.proxifier = proxifier self.daemon_threads = True -# Windows error.h +########################## +# Windows API + +# from Windows' error.h ERROR_INSUFFICIENT_BUFFER = 0x7A +IN6_ADDR = ctypes.c_ubyte * 16 +IN4_ADDR = ctypes.c_ubyte * 4 + + +# +# IPv6 +# + +# https://msdn.microsoft.com/en-us/library/windows/desktop/aa366896(v=vs.85).aspx +class MIB_TCP6ROW_OWNER_PID(ctypes.Structure): + _fields_ = [ + ('ucLocalAddr', IN6_ADDR), + ('dwLocalScopeId', ctypes.wintypes.DWORD), + ('dwLocalPort', ctypes.wintypes.DWORD), + ('ucRemoteAddr', IN6_ADDR), + ('dwRemoteScopeId', ctypes.wintypes.DWORD), + ('dwRemotePort', ctypes.wintypes.DWORD), + ('dwState', ctypes.wintypes.DWORD), + ('dwOwningPid', ctypes.wintypes.DWORD), + ] + + +# https://msdn.microsoft.com/en-us/library/windows/desktop/aa366905(v=vs.85).aspx +def MIB_TCP6TABLE_OWNER_PID(size): + class _MIB_TCP6TABLE_OWNER_PID(ctypes.Structure): + _fields_ = [ + ('dwNumEntries', ctypes.wintypes.DWORD), + ('table', MIB_TCP6ROW_OWNER_PID * size) + ] + + return _MIB_TCP6TABLE_OWNER_PID() -# http://msdn.microsoft.com/en-us/library/windows/desktop/bb485761(v=vs.85).aspx -class MIB_TCPROW2(ctypes.Structure): + +# +# IPv4 +# + +# https://msdn.microsoft.com/en-us/library/windows/desktop/aa366913(v=vs.85).aspx +class MIB_TCPROW_OWNER_PID(ctypes.Structure): _fields_ = [ ('dwState', ctypes.wintypes.DWORD), - ('dwLocalAddr', ctypes.wintypes.DWORD), + ('ucLocalAddr', IN4_ADDR), ('dwLocalPort', ctypes.wintypes.DWORD), - ('dwRemoteAddr', ctypes.wintypes.DWORD), + ('ucRemoteAddr', IN4_ADDR), ('dwRemotePort', ctypes.wintypes.DWORD), ('dwOwningPid', ctypes.wintypes.DWORD), - ('dwOffloadState', ctypes.wintypes.DWORD) ] -# http://msdn.microsoft.com/en-us/library/windows/desktop/bb485772(v=vs.85).aspx -def MIB_TCPTABLE2(size): - class _MIB_TCPTABLE2(ctypes.Structure): - _fields_ = [('dwNumEntries', ctypes.wintypes.DWORD), - ('table', MIB_TCPROW2 * size)] +# https://msdn.microsoft.com/en-us/library/windows/desktop/aa366921(v=vs.85).aspx +def MIB_TCPTABLE_OWNER_PID(size): + class _MIB_TCPTABLE_OWNER_PID(ctypes.Structure): + _fields_ = [ + ('dwNumEntries', ctypes.wintypes.DWORD), + ('table', MIB_TCPROW_OWNER_PID * size) + ] - return _MIB_TCPTABLE2() + return _MIB_TCPTABLE_OWNER_PID() -class TransparentProxy: +TCP_TABLE_OWNER_PID_CONNECTIONS = 4 + + +class TcpConnectionTable(collections.Mapping): + DEFAULT_TABLE_SIZE = 4096 + + def __init__(self): + self._tcp = MIB_TCPTABLE_OWNER_PID(self.DEFAULT_TABLE_SIZE) + self._tcp_size = ctypes.wintypes.DWORD(self.DEFAULT_TABLE_SIZE) + self._tcp6 = MIB_TCP6TABLE_OWNER_PID(self.DEFAULT_TABLE_SIZE) + self._tcp6_size = ctypes.wintypes.DWORD(self.DEFAULT_TABLE_SIZE) + self._map = {} + + def __getitem__(self, item): + return self._map[item] + + def __iter__(self): + return self._map.__iter__() + + def __len__(self): + return self._map.__len__() + + def refresh(self): + self._map = {} + self._refresh_ipv4() + self._refresh_ipv6() + + def _refresh_ipv4(self): + ret = ctypes.windll.iphlpapi.GetExtendedTcpTable( + ctypes.byref(self._tcp), + ctypes.byref(self._tcp_size), + False, + socket.AF_INET, + TCP_TABLE_OWNER_PID_CONNECTIONS, + 0 + ) + if ret == 0: + for row in self._tcp.table[:self._tcp.dwNumEntries]: + local_ip = socket.inet_ntop(socket.AF_INET, bytes(row.ucLocalAddr)) + local_port = socket.htons(row.dwLocalPort) + self._map[(local_ip, local_port)] = row.dwOwningPid + elif ret == ERROR_INSUFFICIENT_BUFFER: + self._tcp = MIB_TCPTABLE_OWNER_PID(self._tcp_size.value) + # no need to update size, that's already done. + self._refresh_ipv4() + else: + raise RuntimeError("[IPv4] Unknown GetExtendedTcpTable return code: %s" % ret) + + def _refresh_ipv6(self): + ret = ctypes.windll.iphlpapi.GetExtendedTcpTable( + ctypes.byref(self._tcp6), + ctypes.byref(self._tcp6_size), + False, + socket.AF_INET6, + TCP_TABLE_OWNER_PID_CONNECTIONS, + 0 + ) + if ret == 0: + for row in self._tcp6.table[:self._tcp6.dwNumEntries]: + local_ip = socket.inet_ntop(socket.AF_INET6, bytes(row.ucLocalAddr)) + local_port = socket.htons(row.dwLocalPort) + self._map[(local_ip, local_port)] = row.dwOwningPid + elif ret == ERROR_INSUFFICIENT_BUFFER: + self._tcp6 = MIB_TCP6TABLE_OWNER_PID(self._tcp6_size.value) + # no need to update size, that's already done. + self._refresh_ipv6() + else: + raise RuntimeError("[IPv6] Unknown GetExtendedTcpTable return code: %s" % ret) + + +def get_local_ip() -> typing.Optional[str]: + # Auto-Detect local IP. This is required as re-injecting to 127.0.0.1 does not work. + # https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("8.8.8.8", 80)) + return s.getsockname()[0] + except OSError: + return None + finally: + s.close() + + +def get_local_ip6(reachable: str) -> typing.Optional[str]: + # The same goes for IPv6, with the added difficulty that .connect() fails if + # the target network is not reachable. + s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) + try: + s.connect((reachable, 80)) + return s.getsockname()[0] + except OSError: + return None + finally: + s.close() + + +class Redirect(threading.Thread): + daemon = True + windivert: pydivert.WinDivert + + def __init__( + self, + handle: typing.Callable[[pydivert.Packet], None], + filter: str, + layer: pydivert.Layer = pydivert.Layer.NETWORK, + flags: pydivert.Flag = 0 + ) -> None: + self.handle = handle + self.windivert = pydivert.WinDivert(filter, layer, flags=flags) + super().__init__() + + def start(self): + self.windivert.open() + super().start() + + def run(self): + while True: + try: + packet = self.windivert.recv() + except WindowsError as e: + if e.winerror == 995: + return + else: + raise + else: + self.handle(packet) + + def shutdown(self): + self.windivert.close() + + def recv(self) -> typing.Optional[pydivert.Packet]: + """ + Convenience function that receives a packet from the passed handler and handles error codes. + If the process has been shut down, None is returned. + """ + try: + return self.windivert.recv() + except WindowsError as e: + if e.winerror == 995: + return None + else: + raise + + +class RedirectLocal(Redirect): + trusted_pids: typing.Set[int] + + def __init__( + self, + redirect_request: typing.Callable[[pydivert.Packet], None], + filter: str + ) -> None: + self.tcp_connections = TcpConnectionTable() + self.trusted_pids = set() + self.redirect_request = redirect_request + super().__init__(self.handle, filter) + + def handle(self, packet): + client = (packet.src_addr, packet.src_port) + + if client not in self.tcp_connections: + self.tcp_connections.refresh() + + # If this fails, we most likely have a connection from an external client. + # In this, case we always want to proxy the request. + pid = self.tcp_connections.get(client, None) + + if pid not in self.trusted_pids: + self.redirect_request(packet) + else: + # It's not really clear why we need to recalculate the checksum here, + # but this was identified as necessary in https://github.com/mitmproxy/mitmproxy/pull/3174. + self.windivert.send(packet, recalculate_checksum=True) + + +TConnection = typing.Tuple[str, int] + +class ClientServerMap: + """A thread-safe LRU dict.""" + connection_cache_size: typing.ClassVar[int] = 65536 + + def __init__(self): + self._lock = threading.Lock() + self._map = collections.OrderedDict() + + def __getitem__(self, item: TConnection) -> TConnection: + with self._lock: + return self._map[item] + + def __setitem__(self, key: TConnection, value: TConnection) -> None: + with self._lock: + self._map[key] = value + self._map.move_to_end(key) + while len(self._map) > self.connection_cache_size: + self._map.popitem(False) + + +class TransparentProxy: """ - Transparent Windows Proxy for mitmproxy based on WinDivert/PyDivert. + Transparent Windows Proxy for mitmproxy based on WinDivert/PyDivert. This module can be used to + redirect both traffic that is forwarded by the host and traffic originating from the host itself. Requires elevated (admin) privileges. Can be started separately by manually running the file. - This module can be used to intercept and redirect all traffic that is forwarded by the user's machine and - traffic sent from the machine itself. - How it works: - (1) First, we intercept all packages that match our filter (destination port 80 and 443 by default). - We both consider traffic that is forwarded by the OS (WinDivert's NETWORK_FORWARD layer) as well as traffic - sent from the local machine (WinDivert's NETWORK layer). In the case of traffic from the local machine, we need to - distinguish between traffc sent from applications and traffic sent from the proxy. To accomplish this, we use - Windows' GetTcpTable2 syscall to determine the source application's PID. + (1) First, we intercept all packages that match our filter. + We both consider traffic that is forwarded by the OS (WinDivert's NETWORK_FORWARD layer) as well + as traffic sent from the local machine (WinDivert's NETWORK layer). In the case of traffic from + the local machine, we need to exempt packets sent from the proxy to not create a redirect loop. + To accomplish this, we use Windows' GetExtendedTcpTable syscall and determine the source + application's PID. For each intercepted package, we 1. Store the source -> destination mapping (address and port) 2. Remove the package from the network (by not reinjecting it). - 3. Re-inject the package into the local network stack, but with the destination address changed to the proxy. + 3. Re-inject the package into the local network stack, but with the destination address + changed to the proxy. - (2) Next, the proxy receives the forwarded packet, but does not know the real destination yet (which we overwrote - with the proxy's address). On Linux, we would now call getsockopt(SO_ORIGINAL_DST), but that unfortunately doesn't - work on Windows. However, we still have the correct source information. As a workaround, we now access the forward - module's API (see APIRequestHandler), submit the source information and get the actual destination back (which the - forward module stored in (1.3)). + (2) Next, the proxy receives the forwarded packet, but does not know the real destination yet + (which we overwrote with the proxy's address). On Linux, we would now call + getsockopt(SO_ORIGINAL_DST). We now access the redirect module's API (see APIRequestHandler), + submit the source information and get the actual destination back (which we stored in 1.1). - (3) The proxy now establish the upstream connection as usual. + (3) The proxy now establishes the upstream connection as usual. - (4) Finally, the proxy sends the response back to the client. To make it work, we need to change the packet's source - address back to the original destination (using the mapping from (1.3)), to which the client believes he is talking - to. + (4) Finally, the proxy sends the response back to the client. To make it work, we need to change + the packet's source address back to the original destination (using the mapping from 1.1), + to which the client believes it is talking to. Limitations: - - No IPv6 support. (Pull Requests welcome) - - 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. - + - We assume that ephemeral TCP ports are not re-used for multiple connections at the same time. + The proxy will fail if an application 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. """ + local: typing.Optional[RedirectLocal] = None + # really weird linting error here. + forward: typing.Optional[Redirect] = None # noqa + response: Redirect + icmp: Redirect + + proxy_port: int + filter: str + + client_server_map: ClientServerMap + + def __init__( + self, + local: bool = True, + forward: bool = True, + proxy_port: int = 8080, + filter: typing.Optional[str] = "tcp.DstPort == 80 or tcp.DstPort == 443", + ) -> None: + self.proxy_port = proxy_port + self.filter = ( + filter + or + f"tcp.DstPort != {proxy_port} and tcp.DstPort != {REDIRECT_API_PORT} and tcp.DstPort < 49152" + ) - def __init__(self, - mode="both", - redirect_ports=(80, 443), custom_filter=None, - proxy_addr=False, proxy_port=8080, - api_host="localhost", api_port=PROXY_API_PORT, - cache_size=65536): - """ - :param mode: Redirection operation mode: "forward" to only redirect forwarded packets, "local" to only redirect - packets originating from the local machine, "both" to redirect both. - :param redirect_ports: if the destination port is in this tuple, the requests are redirected to the proxy. - :param custom_filter: specify a custom WinDivert filter to select packets that should be intercepted. Overrides - redirect_ports setting. - :param proxy_addr: IP address of the proxy (IP within a network, 127.0.0.1 does not work). By default, - this is detected automatically. - :param proxy_port: Port the proxy is listenting on. - :param api_host: Host the forward module API is listening on. - :param api_port: Port the forward module API is listening on. - :param cache_size: Maximum number of connection tuples that are stored. Only relevant in very high - load scenarios. - """ - if proxy_port in redirect_ports: - raise ValueError("The proxy port must not be a redirect port.") - - if not proxy_addr: - # Auto-Detect local IP. - # https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect(("8.8.8.8", 80)) - proxy_addr = s.getsockname()[0] - s.close() - - self.mode = mode - self.proxy_addr, self.proxy_port = proxy_addr, proxy_port - self.connection_cache_size = cache_size - - self.client_server_map = collections.OrderedDict() + self.ipv4_address = get_local_ip() + self.ipv6_address = get_local_ip6("2001:4860:4860::8888") + # print(f"IPv4: {self.ipv4_address}, IPv6: {self.ipv6_address}") + self.client_server_map = ClientServerMap() - self.api = APIServer(self, (api_host, api_port), APIRequestHandler) + self.api = APIServer(self, (REDIRECT_API_HOST, REDIRECT_API_PORT), APIRequestHandler) self.api_thread = threading.Thread(target=self.api.serve_forever) self.api_thread.daemon = True - self.request_filter = custom_filter or " or ".join( - ("tcp.DstPort == %d" % - p) for p in redirect_ports) - self.request_forward_handle: pydivert.WinDivert = None - self.request_forward_thread = threading.Thread( - target=self.request_forward) - self.request_forward_thread.daemon = True - - self.addr_pid_map = dict() - self.trusted_pids = set() - self.tcptable2 = MIB_TCPTABLE2(0) - self.tcptable2_size = ctypes.wintypes.DWORD(0) - self.request_local_handle: pydivert.WinDivert = None - self.request_local_thread = threading.Thread(target=self.request_local) - self.request_local_thread.daemon = True + if forward: + self.forward = Redirect( + self.redirect_request, + self.filter, + pydivert.Layer.NETWORK_FORWARD + ) + if local: + self.local = RedirectLocal( + self.redirect_request, + self.filter + ) # 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: pydivert.WinDivert = None - self.response_thread = threading.Thread(target=self.response) - self.response_thread.daemon = True + self.response = Redirect( + self.redirect_response, + f"outbound and tcp.SrcPort == {proxy_port}", + ) - self.icmp_handle: pydivert.WinDivert = None + # Block all ICMP requests (which are sent on Windows by default). + # If we don't do this, our proxy machine may send an ICMP redirect to the client, + # which instructs the client to directly connect to the real gateway + # if they are on the same network. + self.icmp = Redirect( + lambda _: None, + "icmp", + flags=pydivert.Flag.DROP + ) @classmethod def setup(cls): # TODO: Make sure that server can be killed cleanly. That's a bit difficult as we don't have access to # controller.should_exit when this is called. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server_unavailable = s.connect_ex(("127.0.0.1", PROXY_API_PORT)) + server_unavailable = s.connect_ex((REDIRECT_API_HOST, REDIRECT_API_PORT)) if server_unavailable: proxifier = TransparentProxy() proxifier.start() def start(self): self.api_thread.start() - - # 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 = pydivert.WinDivert( - filter="icmp", - layer=pydivert.Layer.NETWORK, - flags=pydivert.Flag.DROP - ) - self.icmp_handle.open() - - self.response_handle = pydivert.WinDivert( - filter=self.response_filter, - layer=pydivert.Layer.NETWORK - ) - self.response_handle.open() - self.response_thread.start() - - if self.mode == "forward" or self.mode == "both": - self.request_forward_handle = pydivert.WinDivert( - filter=self.request_filter, - 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 = pydivert.WinDivert( - filter=self.request_filter, - layer=pydivert.Layer.NETWORK - ) - self.request_local_handle.open() - self.request_local_thread.start() + self.icmp.start() + self.response.start() + if self.forward: + self.forward.start() + if self.local: + self.local.start() def shutdown(self): - if self.mode == "local" or self.mode == "both": - self.request_local_handle.close() - if self.mode == "forward" or self.mode == "both": - self.request_forward_handle.close() - - self.response_handle.close() - self.icmp_handle.close() + if self.local: + self.local.shutdown() + if self.forward: + self.forward.shutdown() + self.response.shutdown() + self.icmp.shutdown() self.api.shutdown() - 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: - return handle.recv() - except WindowsError as e: - if e.winerror == 995: - return None - else: - raise - - def fetch_pids(self): - ret = ctypes.windll.iphlpapi.GetTcpTable2( - ctypes.byref( - self.tcptable2), ctypes.byref( - self.tcptable2_size), 0) - if ret == ERROR_INSUFFICIENT_BUFFER: - self.tcptable2 = MIB_TCPTABLE2(self.tcptable2_size.value) - self.fetch_pids() - elif ret == 0: - for row in self.tcptable2.table[:self.tcptable2.dwNumEntries]: - local = ( - socket.inet_ntoa(struct.pack('L', row.dwLocalAddr)), - socket.htons(row.dwLocalPort) - ) - self.addr_pid_map[local] = row.dwOwningPid - else: - raise RuntimeError("Unknown GetTcpTable2 return code: %s" % ret) - - def request_local(self): - while True: - packet = self.recv(self.request_local_handle) - if not packet: - return - - client = (packet.src_addr, packet.src_port) - - if client not in self.addr_pid_map: - self.fetch_pids() - - # If this fails, we most likely have a connection from an external client to - # a local server on 80/443. In this, case we always want to proxy - # the request. - pid = self.addr_pid_map.get(client, None) - - if pid not in self.trusted_pids: - self._request(packet) - else: - self.request_local_handle.send(packet, recalculate_checksum=False) - - def request_forward(self): - """ - Redirect packages to the proxy - """ - while True: - packet = self.recv(self.request_forward_handle) - if not packet: - return - - self._request(packet) - - def _request(self, packet: pydivert.Packet): + def redirect_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)) + # print(f"{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: - self.client_server_map.move_to_end(client) + self.client_server_map[client] = (packet.dst_addr, packet.dst_port) + + # We do need to inject to an external IP here, 127.0.0.1 does not work. + if packet.address_family == socket.AF_INET: + assert self.ipv4_address + packet.dst_addr = self.ipv4_address + elif packet.address_family == socket.AF_INET6: + if not self.ipv6_address: + self.ipv6_address = get_local_ip6(packet.src_addr) + assert self.ipv6_address + packet.dst_addr = self.ipv6_address 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 + raise RuntimeError("Unknown address family") + packet.dst_port = self.proxy_port packet.direction = pydivert.consts.Direction.INBOUND - # Use any handle that's on the NETWORK layer - request_local may be - # unavailable. - self.response_handle.send(packet) + # We need a handle on the NETWORK layer. the local handle is not guaranteed to exist, + # so we use the response handle. + self.response.windivert.send(packet) - def response(self): + def redirect_response(self, packet: pydivert.Packet): """ - Spoof source address of packets send from the proxy to the client + If the proxy responds to the client, let the client believe the target server sent the + packets. """ - while True: - packet = self.recv(self.response_handle) - if not packet: - return - - # If the proxy responds to the client, let the client believe the target server sent the packets. - # print(" * Adjust proxy -> client") - client = (packet.dst_addr, packet.dst_port) - 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) - - self.response_handle.send(packet, recalculate_checksum=False) + # print(" * Adjust proxy -> client") + client = (packet.dst_addr, packet.dst_port) + try: + packet.src_addr, packet.src_port = self.client_server_map[client] + except KeyError: + print(f"Warning: Previously unseen connection from proxy to {client}") + else: + packet.recalculate_checksums() + self.response.windivert.send(packet, recalculate_checksum=False) -if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="Windows Transparent Proxy" - ) - parser.add_argument( - '--mode', - choices=[ - 'forward', - 'local', - 'both'], - default="both", - help='redirection operation mode: "forward" to only redirect forwarded packets, ' - '"local" to only redirect packets originating from the local machine') - group = parser.add_mutually_exclusive_group() - group.add_argument( - "--redirect-ports", - nargs="+", - type=int, - default=[ - 80, - 443], - metavar="80", - help="ports that should be forwarded to the proxy") - group.add_argument( - "--custom-filter", - default=None, - metavar="WINDIVERT_FILTER", - help="Custom WinDivert interception rule.") - parser.add_argument("--proxy-addr", default=False, - help="Proxy Server Address") - parser.add_argument("--proxy-port", type=int, default=8080, - help="Proxy Server Port") - parser.add_argument("--api-host", default="localhost", - help="API hostname to bind to") - parser.add_argument("--api-port", type=int, default=PROXY_API_PORT, - help="API port") - parser.add_argument("--cache-size", type=int, default=65536, - help="Maximum connection cache size") - options = parser.parse_args() - proxy = TransparentProxy(**vars(options)) + @contextlib.contextmanager + def exempt(self, pid: int): + if self.local: + self.local.trusted_pids.add(pid) + try: + yield + finally: + if self.local: + self.local.trusted_pids.remove(pid) + + [email protected]() +def cli(): + pass + + [email protected]() [email protected]("--local/--no-local", default=True, + help="Redirect the host's own traffic.") [email protected]("--forward/--no-forward", default=True, + help="Redirect traffic that's forwarded by the host.") [email protected]("--filter", type=str, metavar="WINDIVERT_FILTER", + help="Custom WinDivert interception rule.") [email protected]("-p", "--proxy-port", type=int, metavar="8080", default=8080, + help="The port mitmproxy is listening on.") +def redirect(**options): + """Redirect flows to mitmproxy.""" + proxy = TransparentProxy(**options) proxy.start() - print(" * Transparent proxy active.") - print(" Filter: {0}".format(proxy.request_filter)) + print(f" * Redirection active.") + print(f" Filter: {proxy.request_filter}") try: while True: time.sleep(1) @@ -435,3 +576,16 @@ def response(self): print(" * Shutting down...") proxy.shutdown() print(" * Shut down.") + + [email protected]() +def connections(): + """List all TCP connections and the associated PIDs.""" + connections = TcpConnectionTable() + connections.refresh() + for (ip, port), pid in connections.items(): + print(f"{ip}:{port} -> {pid}") + + +if __name__ == "__main__": + cli()
Support IPv6 transparent proxying on Windows Transparent mode used to work OK on Windows in version 2.0.2. There was an issue with showing correct Host headers however, so I tried to upgrade to 3.0.4 and found that transparent mode now doesn't work at all. On every client request mitmweb shows the following error message: > Transparent mode failure: RuntimeError('Cannot resolve original destination.',) I've tried previous mitmproxy releases and found that this functionality was broken starting from v3.0.0 RC2. I do understand that this mode is not "officially" supported on Windows, but since it used to work, I hope it can be fixed :) ##### Steps to reproduce the problem: 1. Enable IP forwarding (https://gist.github.com/mhils/e9769fab7b1dd0775335) 2. Set port redirection, e.g.: > netsh interface portproxy add v4tov4 listenport=80 connectaddress=192.168.0.90 connectport=8080 > netsh interface portproxy add v4tov4 listenport=443 connectaddress=192.168.0.90 connectport=8080 3. Start mitmproxy in transparent mode: > mitmweb.exe --mode transparent --showhost 4. Install mitmproxy certificate on the phone 5. Set default gateway in phone's Wi-Fi connection properties to the mitmproxy host (e.g. 192.168.0.90) 6. Open any website in phone's browser ##### System information Mitmproxy: 3.0.4 binary Python: 3.6.4 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Windows-10-10.0.16299
Hi, 2.0.2 still works for you but 3.x doesn't? Also where do the netsh rules come from? Normally that's not required, the important part is to have the redirector running (see https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/platform/windows.py#L122) More specifically, it looks like something was broken between the following commits: https://github.com/mitmproxy/mitmproxy/compare/14b33dca5d19afc2427499e25aee8b7439b4b485...40943f5618d0cc9e5ce100df4620aae9cdc236ac Since when I'm trying to install specific revision of mitmproxy from source with --hosts issue fixed (commit 40943f5618d0cc9e5ce100df4620aae9cdc236ac), I get the same error (which I don't get in 2.0.2 release). Can you git-bisect it down to a specific commit? OK, I'll try to do it later. Regarding your questions above - yes, exactly, 2.0.2 still works but 3.x doesn't. netsh rules come from some mitmproxy setup guide for transparent mode (I just changed Linux iptables port redirection rules to its Windows analogues). When I remove these rules, nothing changes - I see the same error. So probably these rules are no longer necessary, but they are not the cause of the problem anyway. Not sure why you closed this. The problem is still present in v4 and v3 with only v2 still working for transparent proxying. Version information I tested this with: ``` Mitmproxy: 4.0.1 Python: 3.6.4 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Windows-10-10.0.17134-SP0 ``` ``` Mitmproxy: 3.0.4 Python: 3.6.4 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Windows-10-10.0.17134-SP0 ``` ``` Mitmproxy version: 2.0.2 (release version) Python version: 3.6.4 Platform: Windows-10-10.0.17134-SP0 SSL version: OpenSSL 1.1.0f 25 May 2017 Windows version: 10 10.0.17134 SP0 Multiprocessor Free ``` @Jazzelhawk Thank you - I've re-opened this, and we'll investigate further. Did a git-bisect to find the specific commit, hope this helps. ``` fab3a8dcf4d7cdce55099172e45a6a0978eac4ab is the first bad commit commit fab3a8dcf4d7cdce55099172e45a6a0978eac4ab Author: Maximilian Hils <[email protected]> Date: Wed Feb 22 22:58:52 2017 +0100 fix constant definition :040000 040000 c11646312e07113d064ff98dd56dbb91d6a38fec a0a6c773bd2dcc2a47aefe980c091320a1e65329 M mitmproxy ```
2018-05-28T16:44:48
mitmproxy/mitmproxy
3,211
mitmproxy__mitmproxy-3211
[ "3180" ]
9ff4f55614eee729aede5aa45bca63026145b8ae
diff --git a/mitmproxy/stateobject.py b/mitmproxy/stateobject.py --- a/mitmproxy/stateobject.py +++ b/mitmproxy/stateobject.py @@ -1,6 +1,7 @@ import typing from typing import Any # noqa from typing import MutableMapping # noqa +import json from mitmproxy.coretypes import serializable from mitmproxy.utils import typecheck @@ -77,8 +78,14 @@ def _process(typeinfo: typecheck.Type, val: typing.Any, make: bool) -> typing.An for k, v in val.items() } elif typename.startswith("typing.Any"): - # FIXME: Remove this when we remove flow.metadata - assert isinstance(val, (int, str, bool, bytes)) + # This requires a bit of explanation. We can't import our IO layer here, + # because it causes a circular import. Rather than restructuring the + # code for this, we use JSON serialization, which has similar primitive + # type restrictions as tnetstring, to check for conformance. + try: + json.dumps(val) + except TypeError: + raise ValueError(f"Data not serializable: {val}") return val else: return typeinfo(val)
diff --git a/test/mitmproxy/test_stateobject.py b/test/mitmproxy/test_stateobject.py --- a/test/mitmproxy/test_stateobject.py +++ b/test/mitmproxy/test_stateobject.py @@ -125,7 +125,7 @@ def test_any(): assert a.x == b.x a = TAny(object()) - with pytest.raises(AssertionError): + with pytest.raises(ValueError): a.get_state()
proxyauth option breaks flow state access in addons ##### Steps to reproduce the problem: 1. Create `test.py` addon ```py from mitmproxy import ctx class AuthTest: def response(self, flow): ctx.log.info('Getting flow state') flow.get_state() ctx.log.info('Got flow state') addons = [ AuthTest() ] ``` 2. Start `mitmdump`, navigate to example.com and observe the log ```bash mitmdump -s server/test.py Loading script server/test.py Proxy server listening at http://*:8080 ... [::1]:56410: GET http://example.com/ << 200 OK 606b Getting flow state Got flow state ``` 3. Re-start `mitmdump` with proxyauth applied and navigate to example.com again ```bash mitmdump -s server/test.py --set proxyauth=foo:bar Loading script server/test.py Proxy server listening at http://*:8080 ... [::1]:56290: GET http://example.com/ << 200 OK 606b Getting flow state Addon error: Traceback (most recent call last): File "server/test.py", line 5, in response flow.get_state() File "/usr/local/Cellar/mitmproxy/4.0.1/libexec/lib/python3.6/site-packages/mitmproxy/flow.py", line 94, in get_state d = super().get_state() File "/usr/local/Cellar/mitmproxy/4.0.1/libexec/lib/python3.6/site-packages/mitmproxy/stateobject.py", line 31, in get_state state[attr] = get_state(cls, val) File "/usr/local/Cellar/mitmproxy/4.0.1/libexec/lib/python3.6/site-packages/mitmproxy/stateobject.py", line 94, in get_state return _process(typeinfo, val, False) File "/usr/local/Cellar/mitmproxy/4.0.1/libexec/lib/python3.6/site-packages/mitmproxy/stateobject.py", line 77, in _process for k, v in val.items() File "/usr/local/Cellar/mitmproxy/4.0.1/libexec/lib/python3.6/site-packages/mitmproxy/stateobject.py", line 77, in <dictcomp> for k, v in val.items() File "/usr/local/Cellar/mitmproxy/4.0.1/libexec/lib/python3.6/site-packages/mitmproxy/stateobject.py", line 81, in _process assert isinstance(val, (int, str, bool, bytes)) AssertionError ``` ##### Any other comments? What have you tried so far? There's a FIXME [right near the code that's breaking](https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/stateobject.py#L80), but I think it's a red herring. My best guess is that proxy auth adds something to the flow state that isn't in the list of allowed types `int, str, bool, bytes`—possibly a `dict`. ##### System information ```bash mitmdump --version Mitmproxy: 4.0.1 Python: 3.6.5 OpenSSL: OpenSSL 1.0.2o 27 Mar 2018 Platform: Darwin-17.5.0-x86_64-i386-64bit ``` <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Thanks for the report! 👍 Yes, this is a bug! The offending type is: `typing.Any` `val = ('foo', 'bar')`, which is a tuple of strings. I think that assert can basically go. We want values to be serialisable, but we don't want to implement a type checker in that spot. This will change once we have the planned session store in place. Thoughts?
2018-06-16T22:26:10
mitmproxy/mitmproxy
3,235
mitmproxy__mitmproxy-3235
[ "3230" ]
3dec4176cfd86a8adf879e76dcf9f9a599bf2996
diff --git a/mitmproxy/tools/console/options.py b/mitmproxy/tools/console/options.py --- a/mitmproxy/tools/console/options.py +++ b/mitmproxy/tools/console/options.py @@ -174,7 +174,7 @@ def keypress(self, size, key): foc, idx = self.get_focus() v = self.walker.get_edit_text() try: - d = self.master.options.parse_setval(foc.opt.name, v) + d = self.master.options.parse_setval(foc.opt, v) self.master.options.update(**{foc.opt.name: d}) except exceptions.OptionsError as v: signals.status_message.send(message=str(v))
Crash when editing str-options ##### Steps to reproduce the problem: 1. Start `mitmproxy` in interactive mode 2. Type `O` to switch to the options view 3. Edit a random `str`-option 4. See `mitmproxy` crash with the following stacktrace: ``` Traceback (most recent call last): File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/mitmproxy/master.py", line 86, in run_loop loop() File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/main_loop.py", line 286, in run self._run() File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/main_loop.py", line 384, in _run self.event_loop.run() File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/main_loop.py", line 1484, in run reraise(*exc_info) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/compat.py", line 58, in reraise raise value File "/usr/lib/python3.6/asyncio/events.py", line 145, in _run self._callback(*self._args) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/raw_display.py", line 404, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/raw_display.py", line 502, in parse_input callback(processed, processed_codes) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/main_loop.py", line 411, in _update self.process_input(keys) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/main_loop.py", line 511, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/mitmproxy/tools/console/window.py", line 309, in keypress k = super().keypress(size, k) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/container.py", line 1131, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/mitmproxy/tools/console/window.py", line 44, in keypress ret = super().keypress(size, key) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/urwid/container.py", line 1131, in keypress return self.body.keypress( (maxcol, remaining), key ) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/mitmproxy/tools/console/options.py", line 283, in keypress return self.focus_item.keypress(tsize, key) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/mitmproxy/tools/console/options.py", line 177, in keypress d = self.master.options.parse_setval(foc.opt.name, v) File "/tmp/mitmproxy-crash/lib/python3.6/site-packages/mitmproxy/optmanager.py", line 332, in parse_setval if o.typespec in (str, typing.Optional[str]): AttributeError: 'str' object has no attribute 'typespec' mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ``` ##### System information ``` Mitmproxy: 4.0.3 Python: 3.6.6 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Linux-4.17.0-x86_64-with-debian-buster-sid ```
2018-07-02T06:12:28
mitmproxy/mitmproxy
3,274
mitmproxy__mitmproxy-3274
[ "3273" ]
5f3cbbb3cd1a8930ec6f9df26cb0d4204391edd7
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -15,6 +15,7 @@ # Default expiry must not be too long: https://github.com/mitmproxy/mitmproxy/issues/815 DEFAULT_EXP = 94608000 # = 24 * 60 * 60 * 365 * 3 +DEFAULT_EXP_DUMMY_CERT = 63072000 # = 2 years # Generated with "openssl dhparam". It's too slow to generate this on startup. DEFAULT_DHPARAM = b""" @@ -101,7 +102,7 @@ def dummy_cert(privkey, cacert, commonname, sans): cert = OpenSSL.crypto.X509() cert.gmtime_adj_notBefore(-3600 * 48) - cert.gmtime_adj_notAfter(DEFAULT_EXP) + cert.gmtime_adj_notAfter(DEFAULT_EXP_DUMMY_CERT) cert.set_issuer(cacert.get_subject()) if commonname is not None and len(commonname) < 64: cert.get_subject().CN = commonname
Reduce certificate validity for Chrome >= 68 ##### Steps to reproduce the problem: 1. Install Chrome 68 2. Start mitmproxy, add mitmproxy-ca to your cert-store 3. Open any site via https 4. Chrome shows NET::ERR_CERT_VALIDITY_TOO_LONG error ##### Any other comments? What have you tried so far? In #815 the validity of the certificates was reduced to three years which was enough for Chrome's "not valid longer than 39 month". It seems like Chrome 68 changed this to a shorter value though I haven't found any evidence in the code yet. After tinkering around I found that the value "71107200" (around 27 month) for DEFAULT_EXP is the greatest value that is accepted by Chrome. I know that I'm not using the most recent version of mitmproxy but the value for DEFAULT_EXP is the same in the current version so I assume the problem is still the same. Suggesting to just reduce the validity to something really short, like Let's Encrypt's three month. Should not be a problem and saves us from further reduction in Chrome. ##### System information -> % mitmproxy --version Mitmproxy: 3.0.3 Python: 3.6.6 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Linux-4.17.8-1-ARCH-x86_64-with-arch
Reducing it to three months means that every mitmproxy user needs to re-install their CA cert very three months.... not very user friendly. I'm open to reducing it a level that makes it valid in Chrome again, e.g., 24 months or similar. @mhils @cortesi? You are absolutely right, my suggestion was not complete: The CA cert can (and should!) have a longer validity. It's the cert for the site that is generated on the fly that should have a shorter validity. The odd thing is: After digging through Chrome's code I did not find any change in the check for the validity: https://chromium.googlesource.com/chromium/src/+/68.0.3440.85/net/cert/cert_verify_proc.cc#894 But still I'm experiencing this problem. Can someone confirm this behaviour? Nevermind...it's this part: https://chromium.googlesource.com/chromium/src/+/68.0.3440.85/net/cert/cert_verify_proc.cc#898 ``` // For certificates issued after 1 March 2018: 825 days. if (start >= time_2018_03_01 && validity_duration > base::TimeDelta::FromDays(825)) { return true; } ``` Diff: https://chromium.googlesource.com/chromium/src/+/1f9eb9f1f6345f1992e54346044dc5022ad50c11%5E%21/net/cert/cert_verify_proc.cc Ballot: https://cabforum.org/2017/03/17/ballot-193-825-day-certificate-lifetimes/ Ok sounds good. Feel free to send a PR that changes the DEFAULT_EXP for issued certs!
2018-07-31T08:20:46
mitmproxy/mitmproxy
3,401
mitmproxy__mitmproxy-3401
[ "3307" ]
6f893a83c090f049e7cebe3335e7a2a32695946b
diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py --- a/mitmproxy/addons/clientplayback.py +++ b/mitmproxy/addons/clientplayback.py @@ -1,6 +1,7 @@ import queue import threading import typing +import time from mitmproxy import log from mitmproxy import controller @@ -94,6 +95,7 @@ def replay(self, f): # pragma: no cover server.wfile.write(http1.assemble_request(r)) server.wfile.flush() + r.timestamp_start = r.timestamp_end = time.time() if f.server_conn: f.server_conn.close()
Client replay doesn't update request timestamps ##### Steps to reproduce the problem: 1. Save flows to a file, `saved.mitm` 2. Wait a few minutes 3. Use a command like `mitmdump -n -C saved.mitm -s myscript.py -w replayed.mtim` to replay the saved flows. 4. Then observe the flows with `mitmproxy -n -r replayed.mitm` and see that the request-response time of the flows are inaccurate because it seems to be calculated using the start time of the requests in `saved.mitm`. ##### Any other comments? What have you tried so far? If such behavior is intentional, what's the recommended way to set the request timestamps so that they reflect the time when the requests are actually replayed rather than the previously saved timestamps? As a workaround, I've added these two lines after the `server.wfile.flush()` line in `addons/clientplayback.py` for my use case: ``` r.timestamp_end = time.time() r.timestamp_start = server.wfile.first_byte_timestamp ``` It seems reasonable but I'm not sure if it's correct. ##### System information Mitmproxy: 4.0.4 Python: 3.7.0 OpenSSL: OpenSSL 1.0.2p 14 Aug 2018 Platform: Darwin-17.5.0-x86_64-i386-64bit
Thanks for the report. I agree - we should probably do a simple ``` request.timestamp_start = request.timestamp_end = time.time() ``` if/before we do client replay. Do you want to submit a PR for this? :)
2018-12-01T12:57:50
mitmproxy/mitmproxy
3,404
mitmproxy__mitmproxy-3404
[ "3072" ]
ce28721458c8cc71de86513a5110676e9763041b
diff --git a/mitmproxy/contentviews/base.py b/mitmproxy/contentviews/base.py --- a/mitmproxy/contentviews/base.py +++ b/mitmproxy/contentviews/base.py @@ -35,32 +35,52 @@ def __call__(self, data: bytes, **metadata) -> TViewResult: raise NotImplementedError() # pragma: no cover -def format_dict( - d: typing.Mapping[TTextType, TTextType] -) -> typing.Iterator[TViewLine]: +def format_pairs( + items: typing.Iterable[typing.Tuple[TTextType, TTextType]] +)-> typing.Iterator[TViewLine]: + """ - Helper function that transforms the given dictionary into a list of + Helper function that accepts a list of (k,v) pairs into a list of [ - ("key", key ) + ("key", key ) ("value", value) ] - entries, where key is padded to a uniform width. + where key is padded to a uniform width """ - max_key_len = max((len(k) for k in d.keys()), default=0) + max_key_len = max((len(k[0]) for k in items), default=0) max_key_len = min((max_key_len, KEY_MAX), default=0) - for key, value in d.items(): + + for key, value in items: if isinstance(key, bytes): + key += b":" else: key += ":" + key = key.ljust(max_key_len + 2) + yield [ ("header", key), ("text", value) ] +def format_dict( + d: typing.Mapping[TTextType, TTextType] +) -> typing.Iterator[TViewLine]: + """ + Helper function that transforms the given dictionary into a list of + [ + ("key", key ) + ("value", value) + ] + entries, where key is padded to a uniform width. + """ + + return format_pairs(d.items()) + + def format_text(text: TTextType) -> typing.Iterator[TViewLine]: """ Helper function that transforms bytes into the view output format. diff --git a/mitmproxy/contentviews/query.py b/mitmproxy/contentviews/query.py --- a/mitmproxy/contentviews/query.py +++ b/mitmproxy/contentviews/query.py @@ -9,6 +9,6 @@ class ViewQuery(base.View): def __call__(self, data, **metadata): query = metadata.get("query") if query: - return "Query", base.format_dict(query) + return "Query", base.format_pairs(query.items(multi=True)) else: return "Query", base.format_text("") diff --git a/mitmproxy/contentviews/urlencoded.py b/mitmproxy/contentviews/urlencoded.py --- a/mitmproxy/contentviews/urlencoded.py +++ b/mitmproxy/contentviews/urlencoded.py @@ -1,5 +1,4 @@ from mitmproxy.net.http import url -from mitmproxy.coretypes import multidict from . import base @@ -13,4 +12,4 @@ def __call__(self, data, **metadata): except ValueError: return None d = url.decode(data) - return "URLEncoded form", base.format_dict(multidict.MultiDict(d)) + return "URLEncoded form", base.format_pairs(d)
diff --git a/test/mitmproxy/contentviews/test_base.py b/test/mitmproxy/contentviews/test_base.py --- a/test/mitmproxy/contentviews/test_base.py +++ b/test/mitmproxy/contentviews/test_base.py @@ -15,3 +15,18 @@ def test_format_dict(): f_d = base.format_dict(d) with pytest.raises(StopIteration): next(f_d) + + +def test_format_pairs(): + d = [("a", "c"), ("b", "d")] + f_d = base.format_pairs(d) + assert next(f_d) + + d = [("abc", "")] + f_d = base.format_pairs(d) + assert next(f_d) + + d = [] + f_d = base.format_pairs(d) + with pytest.raises(StopIteration): + next(f_d) diff --git a/test/mitmproxy/contentviews/test_query.py b/test/mitmproxy/contentviews/test_query.py --- a/test/mitmproxy/contentviews/test_query.py +++ b/test/mitmproxy/contentviews/test_query.py @@ -6,8 +6,8 @@ def test_view_query(): d = "" v = full_eval(query.ViewQuery()) - f = v(d, query=multidict.MultiDict([("foo", "bar")])) + f = v(d, query=multidict.MultiDict([("foo", "bar"), ("foo", "baz")])) assert f[0] == "Query" - assert f[1] == [[("header", "foo: "), ("text", "bar")]] + assert f[1] == [[("header", "foo: "), ("text", "bar")], [("header", "foo: "), ("text", "baz")]] assert v(d) == ("Query", [])
query string arrays are not fully displayed ##### Steps to reproduce the problem: 1. visit through mitmproxy/mitmdump e.g. http://example.com/?first=value&arr[]=foo+bar&arr[]=baz 2. Check the query parameters in the request 3. Notice that they contain more data than mitmproxy/mitmdump shows ##### Any other comments? What have you tried so far? The following script shows all the data: ``` #!/usr/bin/env python3 from urllib.parse import urlparse, parse_qs url = "http://example.com/?first=value&arr[]=foo+bar&arr[]=baz" parts = urlparse(url) print(parse_qs(parts.query)) ``` Output: `{'first': ['value'], 'arr[]': ['foo bar', 'baz']}` But mitmproxy/mitmdump only shows: ``` first: value arr[]: foo bar ``` ##### System information <!-- Paste the output of "mitmproxy --version" here. --> Mitmproxy: 3.0.4 Python: 3.5.2 OpenSSL: OpenSSL 1.0.2g 1 Mar 2016 Platform: Linux-4.10.0-42-generic-x86_64-with-Ubuntu-16.04-xenial <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Repro with curl: ``` curl -x localhost:8080 -k -g "http://example.com/?first=value&arr[]=foo+bar&arr[]=baz" ``` (Note the `-g`) I will to work on this.
2018-12-02T16:55:41
mitmproxy/mitmproxy
3,464
mitmproxy__mitmproxy-3464
[ "2272" ]
70777a1b6ed64af9cafcdef223a8a260ecc96864
diff --git a/mitmproxy/net/http/url.py b/mitmproxy/net/http/url.py --- a/mitmproxy/net/http/url.py +++ b/mitmproxy/net/http/url.py @@ -21,16 +21,25 @@ def parse(url): Raises: ValueError, if the URL is not properly formatted. """ - parsed = urllib.parse.urlparse(url) + # Size of Ascii character after encoding is 1 byte which is same as its size + # But non-Ascii character's size after encoding will be more than its size + def ascii_check(l): + if len(l) == len(str(l).encode()): + return True + return False + + if isinstance(url, bytes): + url = url.decode() + if not ascii_check(url): + url = urllib.parse.urlsplit(url) + url = list(url) + url[3] = urllib.parse.quote(url[3]) + url = urllib.parse.urlunsplit(url) + parsed = urllib.parse.urlparse(url) if not parsed.hostname: raise ValueError("No hostname given") - if isinstance(url, bytes): - host = parsed.hostname - - # this should not raise a ValueError, - # but we try to be very forgiving here and accept just everything. else: host = parsed.hostname.encode("idna") if isinstance(parsed, urllib.parse.ParseResult):
diff --git a/test/mitmproxy/net/http/test_url.py b/test/mitmproxy/net/http/test_url.py --- a/test/mitmproxy/net/http/test_url.py +++ b/test/mitmproxy/net/http/test_url.py @@ -49,6 +49,17 @@ def test_parse(): url.parse('http://lo[calhost') +def test_ascii_check(): + + test_url = "https://xyz.tax-edu.net?flag=selectCourse&lc_id=42825&lc_name=茅莽莽猫氓猫氓".encode() + scheme, host, port, full_path = url.parse(test_url) + assert scheme == b'https' + assert host == b'xyz.tax-edu.net' + assert port == 443 + assert full_path == b'/?flag%3DselectCourse%26lc_id%3D42825%26lc_name%3D%E8%8C%85%E8%8E%BD%E8%8E' \ + b'%BD%E7%8C%AB%E6%B0%93%E7%8C%AB%E6%B0%93' + + @pytest.mark.skipif(sys.version_info < (3, 6), reason='requires Python 3.6 or higher') def test_parse_port_range(): # Port out of range @@ -61,6 +72,7 @@ def test_unparse(): assert url.unparse("http", "foo.com", 80, "/bar") == "http://foo.com/bar" assert url.unparse("https", "foo.com", 80, "") == "https://foo.com:80" assert url.unparse("https", "foo.com", 443, "") == "https://foo.com" + assert url.unparse("https", "foo.com", 443, "*") == "https://foo.com" # We ignore the byte 126: '~' because of an incompatibility in Python 3.6 and 3.7 @@ -131,3 +143,7 @@ def test_unquote(): assert url.unquote("foo") == "foo" assert url.unquote("foo%20bar") == "foo bar" assert url.unquote(surrogates_quoted) == surrogates + + +def test_hostport(): + assert url.hostport(b"https", b"foo.com", 8080) == b"foo.com:8080"
url with Chinese query string return 400 use IE11,url with Chinese query string,return 400. 1. Mitmproxy version: 3.0.0 (release version) Python version: 3.5.3 Platform: Windows-10-10.0.14393-SP0 SSL version: OpenSSL 1.1.0e 16 Feb 2017 Windows version: 10 10.0.14393 SP0 Multiprocessor Free 2. chrome+mitmdump is fine. 3. but use IE11+mitmdump is error. 4. use IE11 + burpsuite is fine. 5. mitmdump --listen-host 127.0.0.1 --listen-port 8080 Mitmproxy was no hint error, but query string **lc_name** was submitted to the charset difference. return HTTP 400. html charset is gb2312. IE11 developer tools see url http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=������� chrome developer tools see url http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=%CD%A8%D3%C3%D6%AA%CA%B6%BA%CD%C4%DC%C1%A6 ![image](https://cloud.githubusercontent.com/assets/1232444/25463418/abe2ef0e-2b28-11e7-827c-ea73b525213c.png)
Thanks for the report. For reference, here is what I believe is the original URL: ``` >>> x = "http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=茅莽莽猫氓猫氓" >>> x.encode("gb2312") b"http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=\xc3\xa9\xc3\xa7\xc3\xa7\xc3\xa8\xc3\xa5\xc3\xa8\xc3\xa5" ``` Unfortunately, there is no encoding provided and this would also be valid UTF-8: ``` >>> x.encode("gb2312").decode("utf8") 'http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=éççèåèå' ``` Whatsoever, looking at https://blogs.msdn.microsoft.com/ieinternals/2012/07/13/brain-dump-international-text/, we should probably just treat it as an opaque collection of bytes. ----------- Non-IE repro for the original bug: ``` λ curl -x localhost:8080 -k 'http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=éççèåèå' ``` ``` 127.0.0.1:53226: HTTP protocol error in client request: Bad HTTP request line: b'GET http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=\xc3\xa9\xc3\xa7\xc3\xa7\xc3\xa8\xc3\xa5\xc3\xa8\xc3\xa5 HTTP/1.1' ``` thanks. uncheck ie11 send utf-8 urls Option. mitmproxy is same as the curl. 127.0.0.1:50800: HTTP protocol error in client request: Bad HTTP request line: b'GET http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=\xcd\xa8\xd3\xc3\xd6\xaa\xca\xb6\xba\xcd\xc4\xdc\xc1\xa6 HTTP/1.1' Ok, the root cause is that we call `urllib.parse.urlparse` [here](https://github.com/mitmproxy/mitmproxy/blob/40f387eb48c192391fcf265e05d0605217b58ea7/mitmproxy/net/http/url.py#L40), which raises a ValueError for the following: ``` >>> import urllib >>> urllib.parse.urlparse(b'http://wlpx.tax-edu.net/jsp/portal/PortalControl?flag=selectCourse&lc_id=42825&lc_name=\xc3\xa9\xc3\xa7\xc3\xa7\xc3\xa8\xc3\xa5\xc3\xa8\xc3\xa5') UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 87: ordinal not in range(128) ``` From https://docs.python.org/3/library/urllib.parse.html: > Applications that need to operate on potentially improperly quoted URLs that may contain non-ASCII data will need to do their own decoding from bytes to characters before invoking the URL parsing methods. decoding from bytes to characters. How do you know what it is encoding charset? Well, yes... that's problem - we simply don't know and there's no information provided. can import chardet? Can we workaround this by detecting non-ascii characters in url and then using urrlib.parse.quote to quote/escape the characters?
2019-02-02T19:27:09
mitmproxy/mitmproxy
3,480
mitmproxy__mitmproxy-3480
[ "3360" ]
70777a1b6ed64af9cafcdef223a8a260ecc96864
diff --git a/mitmproxy/contrib/kaitaistruct/exif_be.py b/mitmproxy/contrib/kaitaistruct/exif_be.py --- a/mitmproxy/contrib/kaitaistruct/exif_be.py +++ b/mitmproxy/contrib/kaitaistruct/exif_be.py @@ -1,12 +1,8 @@ # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -import array -import struct -import zlib -from enum import Enum 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'): @@ -17,6 +13,9 @@ 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.version = self._io.read_u2be() self.ifd0_ofs = self._io.read_u4be() @@ -25,6 +24,9 @@ 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.num_fields = self._io.read_u2be() self.fields = [None] * (self.num_fields) for i in range(self.num_fields): @@ -54,6 +56,9 @@ class FieldTypeEnum(Enum): word = 3 dword = 4 rational = 5 + undefined = 7 + slong = 9 + srational = 10 class TagEnum(Enum): image_width = 256 @@ -518,6 +523,9 @@ 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.tag = self._root.IfdField.TagEnum(self._io.read_u2be()) self.field_type = self._root.IfdField.FieldTypeEnum(self._io.read_u2be()) self.length = self._io.read_u4be() @@ -552,7 +560,7 @@ def data(self): if hasattr(self, '_m_data'): return self._m_data if hasattr(self, '_m_data') else None - if not self.is_immediate_data: + if not (self.is_immediate_data): io = self._root._io _pos = io.pos() io.seek(self.ofs_or_data) diff --git a/mitmproxy/contrib/kaitaistruct/exif_le.py b/mitmproxy/contrib/kaitaistruct/exif_le.py --- a/mitmproxy/contrib/kaitaistruct/exif_le.py +++ b/mitmproxy/contrib/kaitaistruct/exif_le.py @@ -1,12 +1,8 @@ # This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -import array -import struct -import zlib -from enum import Enum 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'): @@ -17,6 +13,9 @@ 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.version = self._io.read_u2le() self.ifd0_ofs = self._io.read_u4le() @@ -25,6 +24,9 @@ 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.num_fields = self._io.read_u2le() self.fields = [None] * (self.num_fields) for i in range(self.num_fields): @@ -54,6 +56,9 @@ class FieldTypeEnum(Enum): word = 3 dword = 4 rational = 5 + undefined = 7 + slong = 9 + srational = 10 class TagEnum(Enum): image_width = 256 @@ -518,6 +523,9 @@ 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.tag = self._root.IfdField.TagEnum(self._io.read_u2le()) self.field_type = self._root.IfdField.FieldTypeEnum(self._io.read_u2le()) self.length = self._io.read_u4le() @@ -552,7 +560,7 @@ def data(self): if hasattr(self, '_m_data'): return self._m_data if hasattr(self, '_m_data') else None - if not self.is_immediate_data: + if not (self.is_immediate_data): io = self._root._io _pos = io.pos() io.seek(self.ofs_or_data)
Error in Auto Content viewer when parsing a JPEG ##### Steps to reproduce the problem: 1. Download those JPEGs: ``` https://img.lemde.fr/2018/10/09/1/0/3008/2005/184/122/60/0/4991a85_fz3CllPV3V0pbxyjvHkXiu7G.jpg https://img.lemde.fr/2018/10/09/0/56/4770/3180/184/122/60/0/2616eb7_ZEmpnu_LH1c1xeTNOJ5uM5uh.jpg ``` Got this error: ``` ERROR: Auto Content viewer failed: ERROR Traceback (most recent call last): ERROR File "mitmproxy/contentviews/__init__.py", line 130, in get_content_view ERROR File "mitmproxy/contentviews/auto.py", line 17, in __call__ ERROR File "mitmproxy/contentviews/image/view.py", line 36, in __call__ ERROR File "mitmproxy/contentviews/image/image_parser.py", line 78, in parse_jpeg ERROR File "mitmproxy/contrib/kaitaistruct/exif_be.py", line 572, in ifd0 ERROR File "mitmproxy/contrib/kaitaistruct/exif_be.py", line 31, in __init__ ERROR File "mitmproxy/contrib/kaitaistruct/exif_be.py", line 522, in __init__ ERROR File "enum.py", line 291, in __call__ ERROR File "enum.py", line 533, in __new__ ERROR File "enum.py", line 546, in _missing_ ERROR ValueError: 9 is not a valid FieldTypeEnum ERROR ``` ##### Any other comments? What have you tried so far? Not sure if those JPEG are malformed, and how mitmproxy should handle this case ##### System information <!-- Paste the output of "mitmproxy --version" here. --> Mitmproxy: 4.0.4 binary Python: 3.6.5 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Darwin-17.7.0-x86_64-i386-64bit <!-- Please use the mitmproxy forums (https://discourse.mitmproxy.org/) for support/how-to questions. Thanks! :) -->
Thanks for the report. We're using the excellent Kaitai Struct to parse images, it looks like their JPEG definition doesn't work for these files. This is an excellent way for first time contributors to help improving mitmproxy: 1. Fix the kaitai struct definition (https://github.com/kaitai-io/kaitai_struct_formats/blob/master/image/jpeg.ksy) to accept the JPEGs. Not sure what field type 9 is, that needs to be investigated. :-) 2. Recompile the ksy file and update https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/jpeg.py 3. Submit a PR to kaitai and mitmproxy! I mirrored the first picture at https://uploads.hi.ls/2018-10/4991a85_fz3CllPV3V0pbxyjvHkXiu7G.jpg in case it goes down. I have started working on this and would update my findings in some time. @prateek1192 Working on this?
2019-02-17T22:45:56
mitmproxy/mitmproxy
3,486
mitmproxy__mitmproxy-3486
[ "2951" ]
70777a1b6ed64af9cafcdef223a8a260ecc96864
diff --git a/mitmproxy/flowfilter.py b/mitmproxy/flowfilter.py --- a/mitmproxy/flowfilter.py +++ b/mitmproxy/flowfilter.py @@ -475,7 +475,30 @@ def _make(): parts.append(f) simplerex = "".join(c for c in pp.printables if c not in "()~'\"") + alphdevanagari = pp.pyparsing_unicode.Devanagari.alphas + alphcyrillic = pp.pyparsing_unicode.Cyrillic.alphas + alphgreek = pp.pyparsing_unicode.Greek.alphas + alphchinese = pp.pyparsing_unicode.Chinese.alphas + alpharabic = pp.pyparsing_unicode.Arabic.alphas + alphhebrew = pp.pyparsing_unicode.Hebrew.alphas + alphjapanese = pp.pyparsing_unicode.Japanese.alphas + alphkorean = pp.pyparsing_unicode.Korean.alphas + alphlatin1 = pp.pyparsing_unicode.Latin1.alphas + alphlatinA = pp.pyparsing_unicode.LatinA.alphas + alphlatinB = pp.pyparsing_unicode.LatinB.alphas + rex = pp.Word(simplerex) |\ + pp.Word(alphcyrillic) |\ + pp.Word(alphgreek) |\ + pp.Word(alphchinese) |\ + pp.Word(alpharabic) |\ + pp.Word(alphdevanagari) |\ + pp.Word(alphhebrew) |\ + pp.Word(alphjapanese) |\ + pp.Word(alphkorean) |\ + pp.Word(alphlatin1) |\ + pp.Word(alphlatinA) |\ + pp.Word(alphlatinB) |\ pp.QuotedString("\"", escChar='\\') |\ pp.QuotedString("'", escChar='\\') for klass in filter_rex:
diff --git a/test/mitmproxy/test_flowfilter.py b/test/mitmproxy/test_flowfilter.py --- a/test/mitmproxy/test_flowfilter.py +++ b/test/mitmproxy/test_flowfilter.py @@ -28,6 +28,9 @@ def test_simple(self): self._dump(p) assert len(p.lst) == 2 + def test_non_ascii(self): + assert flowfilter.parse("~s шгн") + def test_naked_url(self): a = flowfilter.parse("foobar ~h rex") assert a.lst[0].expr == "foobar" @@ -173,10 +176,30 @@ def match_body(self, q, s): assert not self.q("~bq message", q) assert not self.q("~bq message", s) + s.response.text = 'яч' # Cyrillic + assert self.q("~bs яч", s) + s.response.text = '测试' # Chinese + assert self.q('~bs 测试', s) + s.response.text = 'ॐ' # Hindi + assert self.q('~bs ॐ', s) + s.response.text = 'لله' # Arabic + assert self.q('~bs لله', s) + s.response.text = 'θεός' # Greek + assert self.q('~bs θεός', s) + s.response.text = 'לוהים' # Hebrew + assert self.q('~bs לוהים', s) + s.response.text = '神' # Japanese + assert self.q('~bs 神', s) + s.response.text = '하나님' # Korean + assert self.q('~bs 하나님', s) + s.response.text = 'Äÿ' # Latin + assert self.q('~bs Äÿ', s) + assert not self.q("~bs nomatch", s) assert not self.q("~bs content", q) assert not self.q("~bs content", s) assert not self.q("~bs message", q) + s.response.text = 'message' assert self.q("~bs message", s) def test_body(self):
Cannot filter by UTF-8 string ##### Steps to reproduce the problem: 1. run `mitmproxy` 2. type (in UTF-8) `: set view_filter=~bs Троцкий` 3. “Invalid interception filter: ~bs Троцкий” 4. type `: set view_filter=~bs trotskij` 5. the filter is set and correctly limits the view to flows where response body contains “trotskij” ##### Any other comments? What have you tried so far? mitmproxy should make it possible to filter by arbitrary UTF-8 strings. I have `LANG=en_US.UTF-8`; setting `LC_ALL=en_US.UTF-8` doesn’t help. These don’t work, either: - `: set view_filter=~bs "Троцкий"` (the quotes are automatically removed after typing the second one) - `: set "view_filter=~bs Троцкий"` - `: set view_filter=~bs /Троцкий/` ##### System information Mitmproxy: 3.0.3 binary Python: 3.5.2 OpenSSL: OpenSSL 1.1.0g 2 Nov 2017 Platform: Linux-4.4.0-116-generic-x86_64-with-debian-stretch-sid
This might not be an issue of mitmproxy afterall. I think python might not be able to accept the string due to misconfiguration of the terminal emulator. ![deepinscreenshot_select-area_20180304181900](https://user-images.githubusercontent.com/9128903/36945751-94001286-1fd8-11e8-96bf-f8382b43fd3f.png) ![deepinscreenshot_select-area_20180304180343](https://user-images.githubusercontent.com/9128903/36945685-c25ddeb6-1fd7-11e8-8083-3bb430258ada.png) Thanks for reporting this! refs #2801
2019-02-23T20:25:32
mitmproxy/mitmproxy
3,516
mitmproxy__mitmproxy-3516
[ "3266" ]
8353f4a55afeec9d30727d91d642e8b8af4040f8
diff --git a/mitmproxy/tools/_main.py b/mitmproxy/tools/_main.py --- a/mitmproxy/tools/_main.py +++ b/mitmproxy/tools/_main.py @@ -87,7 +87,7 @@ def run( arg_check.check() sys.exit(1) try: - opts.confdir = args.confdir + opts.set(*args.setoptions, defer=True) optmanager.load_paths( opts, os.path.join(opts.confdir, OPTIONS_FILE_NAME), @@ -110,7 +110,6 @@ def run( if args.commands: master.commands.dump() sys.exit(0) - opts.set(*args.setoptions, defer=True) if extra: opts.update(**extra(args)) diff --git a/mitmproxy/tools/cmdline.py b/mitmproxy/tools/cmdline.py --- a/mitmproxy/tools/cmdline.py +++ b/mitmproxy/tools/cmdline.py @@ -20,12 +20,6 @@ def common_options(parser, opts): action='store_true', help="Show all commands and their signatures", ) - parser.add_argument( - "--confdir", - type=str, dest="confdir", default=core.CONF_DIR, - metavar="PATH", - help="Path to the mitmproxy config directory" - ) parser.add_argument( "--set", type=str, dest="setoptions", default=[],
Confusing confdir argument My tests are messy cause I used mitmproxy and mitmdump, both of them in 4.0.1 and 4.0.3 and now I mixed all cases. At some point, I think I had an error saying that --confdir was deprecated and had to use "--set confdir=" (I can't reproduce this case though with mitmproxy or mitmdump...) I spent some time to try to make "--set confdir=" work in a weird bash script and arguments with quotes and maybe it failed due to me. But I realized --confdir was still working eventually for mitmdump in 4.0.3. Question to sum up: Is it attended to have both "--confdir" and "--set confdir=" working at the same time for mitmproxy & mitmdump? If yes, help (-h) should specify it clearly with something like: "--confdir PATH, --set confdir=PATH" If not, one of them should be deleted.
@tomlabaude Hello! I checked your case for both mitmproxy and mitmdump (latest version from the master branch). `--confdir` is deprecated for newest mitmproxy as well as for newest mitmdump and only `--set confdir=` is available. You can read more about mitmproxy options here -> https://docs.mitmproxy.org/stable/concepts-options/ In response to your question. Since deprecation list has `confdir` inside (https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/arg_check.py#L4), then no, it isn't meant to have both `--confdir` and `--set confdir=` - only `--set confdir`. And yes, we should delete `--confdir` from `--help` output. Thanks :)
2019-04-09T20:25:40
mitmproxy/mitmproxy
3,525
mitmproxy__mitmproxy-3525
[ "3502" ]
8353f4a55afeec9d30727d91d642e8b8af4040f8
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 @@ -304,7 +304,7 @@ def refresh_set_cookie_header(c: str, delta: int) -> str: e = email.utils.parsedate_tz(attrs["expires"]) if e: f = email.utils.mktime_tz(e) + delta - attrs.set_all("expires", [email.utils.formatdate(f)]) + attrs.set_all("expires", [email.utils.formatdate(f, usegmt=True)]) else: # This can happen when the expires tag is invalid. # reddit.com sends a an expires tag like this: "Thu, 31 Dec 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 @@ -186,7 +186,7 @@ def refresh(self, now=None): d = parsedate_tz(self.headers[i]) if d: new = mktime_tz(d) + delta - self.headers[i] = formatdate(new) + self.headers[i] = formatdate(new, usegmt=True) c = [] for set_cookie_header in self.headers.get_all("set-cookie"): try:
diff --git a/test/mitmproxy/net/http/test_response.py b/test/mitmproxy/net/http/test_response.py --- a/test/mitmproxy/net/http/test_response.py +++ b/test/mitmproxy/net/http/test_response.py @@ -148,7 +148,7 @@ def test_set_cookies(self): def test_refresh(self): r = tresp() n = time.time() - r.headers["date"] = email.utils.formatdate(n) + r.headers["date"] = email.utils.formatdate(n, usegmt=True) pre = r.headers["date"] r.refresh(946681202) assert pre == r.headers["date"]
Server replay corrupts Date header ##### Steps to reproduce the problem: 1. Start `mitmproxy`. 2. Run a request through it and observe that the `Date` header of the response is correct: $ curl -six http://localhost:8080 http://httpbin.org/status/200 | grep Date: Date: Thu, 21 Mar 2019 12:45:00 GMT 3. In mitmproxy, start server replay: : replay.server @all 4. Run a request again and observe that the `Date` header now has `-0000` instead of `GMT`: $ curl -six http://localhost:8080 http://httpbin.org/status/200 | grep Date: Date: Thu, 21 Mar 2019 12:46:58 -0000 ##### Any other comments? What have you tried so far? Per [RFC 7231 § 7.1.1](https://tools.ietf.org/html/rfc7231#section-7.1.1), a correct HTTP date always has `GMT`. ##### System information Mitmproxy: 4.0.4 binary Python: 3.6.3 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Linux-4.15.0-46-generic-x86_64-with-debian-buster-sid
Thanks! The culprit is here somewhere: https://github.com/mitmproxy/mitmproxy/blob/8353f4a55afeec9d30727d91d642e8b8af4040f8/mitmproxy/addons/serverplayback.py#L182 https://github.com/mitmproxy/mitmproxy/blob/8353f4a55afeec9d30727d91d642e8b8af4040f8/mitmproxy/net/http/response.py#L168
2019-04-17T01:58:30
mitmproxy/mitmproxy
3,675
mitmproxy__mitmproxy-3675
[ "3559" ]
eb7ed1dc40025dd9eada5b01852fc20106a4a204
diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py --- a/mitmproxy/addons/clientplayback.py +++ b/mitmproxy/addons/clientplayback.py @@ -203,8 +203,9 @@ def start_replay(self, flows: typing.Sequence[flow.Flow]) -> None: # https://github.com/mitmproxy/mitmproxy/issues/2197 if hf.request.http_version == "HTTP/2.0": hf.request.http_version = "HTTP/1.1" - host = hf.request.headers.pop(":authority") - hf.request.headers.insert(0, "host", host) + host = hf.request.headers.pop(":authority", None) + if host is not None: + hf.request.headers.insert(0, "host", host) self.q.put(hf) ctx.master.addons.trigger("update", lst)
removing ":authority" pseudo header, then executing request crashes mitmproxy ##### Steps to reproduce the problem: 1. Run mitmproxy 2. Visit some http2 website, e.g. google.com 3. Edit the request (enter + e + 7) and remove the :authority header (d + q). 4. Replay the request (r). 5. mitmproxy crashes Stacktrace: Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/mitmproxy/master.py", line 86, in run_loop loop()oding: gzip, deflate, br File "/usr/lib/python3.7/site-packages/urwid/main_loop.py", line 286, in run self._run()e-requests: 1 File "/usr/lib/python3.7/site-packages/urwid/main_loop.py", line 384, in _run self.event_loop.run() tab to view [m:auto] File "/usr/lib/python3.7/site-packages/urwid/main_loop.py", line 1484, in run reraise(*exc_info) File "/usr/lib/python3.7/site-packages/urwid/compat.py", line 58, in reraise raise value File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/usr/lib/python3.7/site-packages/urwid/raw_display.py", line 404, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/usr/lib/python3.7/site-packages/urwid/raw_display.py", line 502, in parse_input callback(processed, processed_codes) File "/usr/lib/python3.7/site-packages/urwid/main_loop.py", line 411, in _update self.process_input(keys) File "/usr/lib/python3.7/site-packages/urwid/main_loop.py", line 511, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/lib/python3.7/site-packages/mitmproxy/tools/console/window.py", line 313, in keypress k File "/usr/lib/python3.7/site-packages/mitmproxy/tools/console/keymap.py", line 143, in handle return self.executor(b.command) File "/usr/lib/python3.7/site-packages/mitmproxy/tools/console/commandexecutor.py", line 17, in __call__ ret = self.master.commands.execute(cmd) File "/usr/lib/python3.7/site-packages/mitmproxy/command.py", line 245, in execute return self.call_strings(parts[0], parts[1:]) File "/usr/lib/python3.7/site-packages/mitmproxy/command.py", line 233, in call_strings return self.commands[path].call(args) File "/usr/lib/python3.7/site-packages/mitmproxy/command.py", line 105, in call ret = self.func(*self.prepare_args(args)) File "/usr/lib/python3.7/site-packages/mitmproxy/command.py", line 275, in wrapper return function(*args, **kwargs) File "/usr/lib/python3.7/site-packages/mitmproxy/addons/clientplayback.py", line 204, in start_replay host = hf.request.headers.pop(":authority") File "/usr/lib/python3.7/_collections_abc.py", line 795, in pop value = self[key] File "/usr/lib/python3.7/site-packages/mitmproxy/coretypes/multidict.py", line 39, in __getitem__ raise KeyError(key) KeyError: ':authority' mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ##### System information Mitmproxy: 4.0.4 Python: 3.7.3 OpenSSL: OpenSSL 1.1.1c 28 May 2019 Platform: Linux-5.1.6-arch1-1-ARCH-x86_64-with-arch
2019-10-25T08:43:54
mitmproxy/mitmproxy
3,698
mitmproxy__mitmproxy-3698
[ "3694" ]
dac0bfe786a8d1dfdd97f29d6bb262ed258153fa
diff --git a/mitmproxy/addons/view.py b/mitmproxy/addons/view.py --- a/mitmproxy/addons/view.py +++ b/mitmproxy/addons/view.py @@ -238,18 +238,24 @@ def focus_next(self) -> None: """ Set focus to the next flow. """ - idx = self.focus.index + 1 - if self.inbounds(idx): - self.focus.flow = self[idx] + if self.focus.index is not None: + idx = self.focus.index + 1 + if self.inbounds(idx): + self.focus.flow = self[idx] + else: + pass @command.command("view.focus.prev") def focus_prev(self) -> None: """ Set focus to the previous flow. """ - idx = self.focus.index - 1 - if self.inbounds(idx): - self.focus.flow = self[idx] + if self.focus.index is not None: + idx = self.focus.index - 1 + if self.inbounds(idx): + self.focus.flow = self[idx] + else: + pass # Order @command.command("view.order.options")
Command view.focus.[next|prev] causes mitmproxy to crash #### Problem Description `mitmproxy` crashes if one tries to run the command `view.focus.next` or `view.focus.prev` when there are no flows in it yet #### Steps to reproduce the behavior: 1. Open mitmproxy making sure there are no clients using it 2. In the main screen press `:` and then enter the command `view.focus.next` 3. Press `Return` and notice that the application crashes #### System Information $ mitmproxy --version Mitmproxy: 4.0.4 Python: 3.7.3 OpenSSL: OpenSSL 1.1.1b 26 Feb 2019 Platform: Linux-5.0.0-31-generic-x86_64-with-Ubuntu-19.04-disco
2019-11-14T18:02:19
mitmproxy/mitmproxy
3,705
mitmproxy__mitmproxy-3705
[ "3469", "3469" ]
698f7e2e177baf313e6af62ec0f79a26693e430b
diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py --- a/mitmproxy/addons/clientplayback.py +++ b/mitmproxy/addons/clientplayback.py @@ -1,23 +1,23 @@ import queue import threading -import typing import time +import typing -from mitmproxy import log +import mitmproxy.types +from mitmproxy import command +from mitmproxy import connections from mitmproxy import controller +from mitmproxy import ctx from mitmproxy import exceptions -from mitmproxy import http from mitmproxy import flow +from mitmproxy import http +from mitmproxy import io +from mitmproxy import log from mitmproxy import options -from mitmproxy import connections +from mitmproxy.coretypes import basethread from mitmproxy.net import server_spec, tls from mitmproxy.net.http import http1 -from mitmproxy.coretypes import basethread from mitmproxy.utils import human -from mitmproxy import ctx -from mitmproxy import io -from mitmproxy import command -import mitmproxy.types class RequestReplayThread(basethread.BaseThread): @@ -117,7 +117,7 @@ def replay(self, f): # pragma: no cover finally: r.first_line_format = first_line_format_backup f.live = False - if server.connected(): + if server and server.connected(): server.finish() server.close() diff --git a/mitmproxy/addons/serverplayback.py b/mitmproxy/addons/serverplayback.py --- a/mitmproxy/addons/serverplayback.py +++ b/mitmproxy/addons/serverplayback.py @@ -1,16 +1,19 @@ import hashlib -import urllib import typing +import urllib -from mitmproxy import ctx -from mitmproxy import flow +import mitmproxy.types +from mitmproxy import command +from mitmproxy import ctx, http from mitmproxy import exceptions +from mitmproxy import flow from mitmproxy import io -from mitmproxy import command -import mitmproxy.types class ServerPlayback: + flowmap: typing.Dict[typing.Hashable, typing.List[http.HTTPFlow]] + configured: bool + def __init__(self): self.flowmap = {} self.configured = False @@ -82,10 +85,10 @@ def load_flows(self, flows: typing.Sequence[flow.Flow]) -> None: Replay server responses from flows. """ self.flowmap = {} - for i in flows: - if i.response: # type: ignore - l = self.flowmap.setdefault(self._hash(i), []) - l.append(i) + for f in flows: + if isinstance(f, http.HTTPFlow): + lst = self.flowmap.setdefault(self._hash(f), []) + lst.append(f) ctx.master.addons.trigger("update", []) @command.command("replay.server.file") @@ -108,12 +111,11 @@ def clear(self) -> None: def count(self) -> int: return sum([len(i) for i in self.flowmap.values()]) - def _hash(self, flow): + def _hash(self, flow: http.HTTPFlow) -> typing.Hashable: """ Calculates a loose hash of the flow request. """ r = flow.request - _, _, path, _, query, _ = urllib.parse.urlparse(r.url) queriesArray = urllib.parse.parse_qsl(query, keep_blank_values=True) @@ -158,20 +160,32 @@ def _hash(self, flow): repr(key).encode("utf8", "surrogateescape") ).digest() - def next_flow(self, request): + def next_flow(self, flow: http.HTTPFlow) -> typing.Optional[http.HTTPFlow]: """ Returns the next flow object, or None if no matching flow was found. """ - hsh = self._hash(request) - if hsh in self.flowmap: + hash = self._hash(flow) + if hash in self.flowmap: if ctx.options.server_replay_nopop: - return self.flowmap[hsh][0] + return next(( + flow + for flow in self.flowmap[hash] + if flow.response + ), None) else: - ret = self.flowmap[hsh].pop(0) - if not self.flowmap[hsh]: - del self.flowmap[hsh] + ret = self.flowmap[hash].pop(0) + while not ret.response: + if self.flowmap[hash]: + ret = self.flowmap[hash].pop(0) + else: + del self.flowmap[hash] + return None + if not self.flowmap[hash]: + del self.flowmap[hash] return ret + else: + return None def configure(self, updated): if not self.configured and ctx.options.server_replay: @@ -182,10 +196,11 @@ def configure(self, updated): raise exceptions.OptionsError(str(e)) self.load_flows(flows) - def request(self, f): + def request(self, f: http.HTTPFlow) -> None: if self.flowmap: rflow = self.next_flow(f) if rflow: + assert rflow.response response = rflow.response.copy() response.is_replay = True if ctx.options.server_replay_refresh: @@ -197,4 +212,5 @@ def request(self, f): f.request.url ) ) + assert f.reply f.reply.kill()
diff --git a/test/mitmproxy/addons/test_serverplayback.py b/test/mitmproxy/addons/test_serverplayback.py --- a/test/mitmproxy/addons/test_serverplayback.py +++ b/test/mitmproxy/addons/test_serverplayback.py @@ -1,13 +1,13 @@ import urllib -import pytest -from mitmproxy.test import taddons -from mitmproxy.test import tflow +import pytest import mitmproxy.test.tutils -from mitmproxy.addons import serverplayback from mitmproxy import exceptions from mitmproxy import io +from mitmproxy.addons import serverplayback +from mitmproxy.test import taddons +from mitmproxy.test import tflow def tdump(path, flows): @@ -321,7 +321,7 @@ def test_server_playback_full(): with taddons.context(s) as tctx: tctx.configure( s, - server_replay_refresh = True, + server_replay_refresh=True, ) f = tflow.tflow() @@ -345,7 +345,7 @@ def test_server_playback_kill(): with taddons.context(s) as tctx: tctx.configure( s, - server_replay_refresh = True, + server_replay_refresh=True, server_replay_kill_extra=True ) @@ -357,3 +357,25 @@ def test_server_playback_kill(): f.request.host = "nonexistent" tctx.cycle(s, f) assert f.reply.value == exceptions.Kill + + +def test_server_playback_response_deleted(): + """ + The server playback addon holds references to flows that can be modified by the user in the meantime. + One thing that can happen is that users remove the response object. This happens for example when doing a client + replay at the same time. + """ + sp = serverplayback.ServerPlayback() + with taddons.context(sp) as tctx: + tctx.configure(sp) + f1 = tflow.tflow(resp=True) + f2 = tflow.tflow(resp=True) + + assert not sp.flowmap + + sp.load_flows([f1, f2]) + assert sp.flowmap + + f1.response = f2.response = None + assert not sp.next_flow(f1) + assert not sp.flowmap
Errors when trying to use server replay on the flows created with help of mitmproxy ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `n` -> `enter` -> `r` 3. Press `:` -> input "replay.server @focus" -> `enter` -> `r` ![image](https://user-images.githubusercontent.com/20267977/52443176-b7484400-2b2d-11e9-8c8f-dfcae3b6f898.png) 4. Create second flow using "n -> enter -> r" sequence. 5. Press `:` -> input `replay.server @all` -> `enter` -> replay any flow. ![image](https://user-images.githubusercontent.com/20267977/52443359-26be3380-2b2e-11e9-8521-87bb7934d783.png) ##### System information Mitmproxy: 5.0.0.dev (+223, commit 139a385) Python: 3.6.7 OpenSSL: OpenSSL 1.0.2g 1 Mar 2016 Platform: Linux-4.4.0-141-generic-x86_64-with-Ubuntu-16.04-xenial Errors when trying to use server replay on the flows created with help of mitmproxy ##### Steps to reproduce the problem: 1. Run mitmproxy. 2. Press `n` -> `enter` -> `r` 3. Press `:` -> input "replay.server @focus" -> `enter` -> `r` ![image](https://user-images.githubusercontent.com/20267977/52443176-b7484400-2b2d-11e9-8c8f-dfcae3b6f898.png) 4. Create second flow using "n -> enter -> r" sequence. 5. Press `:` -> input `replay.server @all` -> `enter` -> replay any flow. ![image](https://user-images.githubusercontent.com/20267977/52443359-26be3380-2b2e-11e9-8521-87bb7934d783.png) ##### System information Mitmproxy: 5.0.0.dev (+223, commit 139a385) Python: 3.6.7 OpenSSL: OpenSSL 1.0.2g 1 Mar 2016 Platform: Linux-4.4.0-141-generic-x86_64-with-Ubuntu-16.04-xenial
2019-11-15T16:14:55
mitmproxy/mitmproxy
3,714
mitmproxy__mitmproxy-3714
[ "3695" ]
70e3871fdb066fa4267cfb44df36e24f9986e3e7
diff --git a/mitmproxy/net/tcp.py b/mitmproxy/net/tcp.py --- a/mitmproxy/net/tcp.py +++ b/mitmproxy/net/tcp.py @@ -558,7 +558,7 @@ def __init__(self, address): self.socket = None try: - # First try to bind an IPv6 socket, with possible IPv4 if the OS supports it. + # First try to bind an IPv6 socket, attempting to enable IPv4 support if the OS supports it. # This allows us to accept connections for ::1 and 127.0.0.1 on the same socket. # Only works if self.address == "" self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) @@ -572,8 +572,20 @@ def __init__(self, address): self.socket = None if not self.socket: - # Binding to an IPv6 socket failed, lets fall back to IPv4. - self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + # Binding to an IPv6 + IPv4 socket failed, lets fall back to IPv4 only. + self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + self.socket.bind(self.address) + except socket.error: + if self.socket: + self.socket.close() + self.socket = None + + if not self.socket: + # Binding to an IPv4 only socket failed, lets fall back to IPv6 only. + self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.socket.bind(self.address)
Add IPv6-only mode **Is your feature request related to a problem? Please describe.** When starting the proxy on a machine that has IPv4 disabled, the proxy fails to start. Taking a look at the code, it seems that issue occurs when the socket option IPV6_V6ONLY is set to 0 and the system does not allow IPv4-enabled sockets. #### Describe the solution you'd like Adding an ipv6_only option was pretty quick & easy, and I have a potential patch, but I wanted to see if this is a reasonable thing to do? #### Describe alternatives you've considered It could also make sense to--instead of adding an ipv6_only option--add an option that gives the user full control to select ipv6_only, ipv4_only, or both ipv4 + ipv6, where the proxy does not attempt to fall back on another protocol.
You were probably looking at https://github.com/mitmproxy/mitmproxy/blob/dac0bfe786a8d1dfdd97f29d6bb262ed258153fa/mitmproxy/net/tcp.py#L560-L579? Can we make it work out of the box without an extra option? For example, we could try 6+4, first, then 4, then 6? Yup, that's exactly what I was looking at. I think the no-option route works. Do you have a preference toward trying 6+4 -> 4 -> 6? If line 567 is updated to be set conditionally, then we would end up trying 6+4 -> 6 -> 4. And that seems to line up with the comment on line 561: "possible IPv4". Thoughts? What do you have in mind when you say "updated to be set conditionally"? Only if `address[0] == ""`? That would be sad, because (for example) `address == ("localhost",8000)` works with IPV6_V6ONLY=0 on Windows. I think we should always try to disable IPV6_V6ONLY, even if that comes at the cost of having to try again. If we need to try again anways, I would have a slight preference for 6+4 -> 4 -> 6 as that may spare us a few support requests. It ends up with v6 anyways in your case. :) Sorry, didn't exactly phrase that one well. What I was thinking was: always **try** to disable IPV6_V6ONLY, but continue binding to the IPv6-only socket if disabling IPV6_V6ONLY fails. That said, since IPv6-only will be possible in either case, I'm not too picky here. Whatever makes life easier.
2019-11-18T23:11:59
mitmproxy/mitmproxy
3,717
mitmproxy__mitmproxy-3717
[ "3704" ]
223335111d3923ef6be8e01259b315ddf390c45c
diff --git a/mitmproxy/tools/console/common.py b/mitmproxy/tools/console/common.py --- a/mitmproxy/tools/console/common.py +++ b/mitmproxy/tools/console/common.py @@ -369,18 +369,15 @@ def raw_format_table(f): req = [] cursor = [' ', 'focus'] - if f.get('resp_is_replay', False): - cursor[0] = SYMBOL_REPLAY - cursor[1] = 'replay' - if f['marked']: - if cursor[0] == ' ': - cursor[0] = SYMBOL_MARK - cursor[1] = 'mark' if f['focus']: cursor[0] = '>' - req.append(fcol(*cursor)) + if f.get('resp_is_replay', False) or f.get('req_is_replay', False): + req.append(fcol(SYMBOL_REPLAY, 'replay')) + if f['marked']: + req.append(fcol(SYMBOL_MARK, 'mark')) + if f["two_line"]: req.append(TruncatedText(f["req_url"], colorize_url(f["req_url"]), 'left')) pile.append(urwid.Columns(req, dividechars=1))
New Table UI has no replay indicator #### Problem Description The new table UI doesn't show that a flow has been replayed: ![image](https://user-images.githubusercontent.com/1019198/68954563-90a5f080-07c4-11ea-9d73-3abf9ce674b3.png) The two-line UI still has an indicator - `[r]` in my case as my terminal is detected to not support UTF8: ![image](https://user-images.githubusercontent.com/1019198/68954680-cb0f8d80-07c4-11ea-91d0-af110277d143.png) #### Steps to reproduce the behavior: 1. Add a flow, e.g. by pressing `n` `enter` 2. Press `r` to replay. #### System Information Mitmproxy: 5.0.0.dev (+356, commit a5412ab) Python: 3.8.0 OpenSSL: OpenSSL 1.1.1 11 Sep 2018 Platform: Linux-4.4.0-18362-Microsoft-x86_64-with-glibc2.27
@Jessonsotoventura: You are the expert here - would you mind taking a look? 😊 Yes - I'll take a look at this issue The issue seems to be here: <https://github.com/mitmproxy/mitmproxy/blob/ac22aee2f512cefd298fe0d9563a5de0ef7e42ee/mitmproxy/tools/console/common.py#L371-L380> 2 things that caught my attention: The line ` if f.get('resp_is_replay', False):` should probably be ` if f.get('req_is_replay', False):` And even if that is true, the last if there `if f['focus']:` overwrites the cursor with a `>` if there is only 1 flow in the table (after all you will be focusing it). The replay symbol should be drawn on the second column, not the first. Hopefully this is helpful
2019-11-20T03:40:59
mitmproxy/mitmproxy
3,735
mitmproxy__mitmproxy-3735
[ "3733" ]
f026285434a3800eef4284ff2d662d4d0c9a2d84
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 @@ -242,6 +242,8 @@ def __call__(self): self._client_hello = net_tls.ClientHello.from_file(self.client_conn.rfile) except exceptions.TlsProtocolException as e: self.log("Cannot parse Client Hello: %s" % repr(e), "error") + # Without knowning the ClientHello we cannot proceed in this connection. + return # Do we need to do a server handshake now? # There are two reasons why we would want to establish TLS with the server now:
Cannot parse client hello Hi! I’m trying to capture the traffic in android10 machines with no rooting. So I added the mitmproxy certificate as the user certificate. It pretty works well in the Chrome browser but in https://play.google.com/store/apps/details?id=com.nhn.android.search&hl=ko this browser I got crash with this link https://abr.ge/cctk0 I think it's async socket timing issue but I'm not sure about it. Is there some one can help to debug it? ::ffff:127.0.0.1:65290: Cannot parse Client Hello: TlsProtocolException('Cannot read raw Client Hello: TlsProtocolException(\'Unexpected EOF in TLS handshake: b\\\'\\\\x01\\\\x00\\\\x01\\\\xfc\\\\x03\\\\x03\\\\xd6_\\\\x11\\\\x1fo\\\\xd3P\\\\xb1\\\\x86\\\\x18\\\\\\\\\\\\xf0(\\\\xbf\\\\xa2(X\\\\xda#q\\\\xe8\\\\x91\\\\x80\\\\xfd\\\\x0bAv7\\\\xe7\\\\x12\\\\x0b\\\\xbd :\\\\xd5\\\\xfdu\\\\x9bn\\\\xb7py-\\\\xec\\\\xc0\\\\xf0%\\\\x01\\\\xb3S\\\\x0f}\\\\xa1")w\\\\x06\\\\x17\\\\xe1\\\\x1d\\\\x16,\\\\xb5\\\\xdf*\\\\x00\\\\x1c**\\\\xc0+\\\\xc0/\\\\xc0,\\\\xc00\\\\xcc\\\\xa9\\\\xcc\\\\xa8\\\\xc0\\\\x13\\\\xc0\\\\x14\\\\x00\\\\x9c\\\\x00\\\\x9d\\\\x00/\\\\x005\\\\x00\\\\n\\\\x01\\\\x00\\\\x01\\\\x97\\\\x1a\\\\x1a\\\\x00\\\\x00\\\\xff\\\\x01\\\\x00\\\\x01\\\\x00\\\\x00\\\\x00\\\\x00\\\\x17\\\\x00\\\\x15\\\\x00\\\\x00\\\\x12ablog.airbridge.io\\\\x00\\\\x17\\\\x00\\\\x00\\\\x00#\\\\x00\\\\xb0\\\\x88\\\\xf4F\\\\xba\\\\x9c*\\\\xba\\\\x85\\\\x10\\\\\\\'h\\\\x17\\\\xe0y5)\\\\xf8\\\\x843Km\\\\xd5 \\\\x1cX98x\\\\xf66O7y{\\\\xc1\\\\xe1c:E\\\\xebL\\\\x18 L}\\\\x05`\\\\xb8!.\\\\xba\\\\xac\\\\x88]\\\\x0e7\\\\x0b\\\\xc0V\\\\xcd\\\\xd5/\\\\xb79\\\\x01o\\\\x0e\\\\xbc\\\\xd1\\\\x8a\\\\x13\\\\x82\\\\x8e\\\\x84;Z\\\\xdf\\\\xaf\\\\x15\\\\xfe\\\\xf9`2\\\\xe1\\\\x13C\\\\xbb\\\\x03\\\\x88\\\\xe1]%\\\\xe2\\\\r=(\\\\xf4\\\\x0e\\\\xb8\\\\xc3\\\\x08S\\\\xed\\\\xad\\\\xe3\\\\xca\\\\xd9p\\\\xb1\\\\x81\\\\x1c\\\\xfeU\\\\x82C\\\\xdd\\\\x0c\\\\xf8\\\\rZ\\\\xaf\\\\xeeD\\\\xf0\\\\x8eW\\\\x10[\\\\\\\\E9\\\\x95m\\\\\\\\\\\\xa8\\\\xef_\\\\x1a\\\\x1b\\\\xadbU\\\\xaa\\\\n\\\\xb8\\\\x89\\\\x85-\\\\xeav\\\\x1ev\\\\xd6\\\\xc5\\\\x8b\\\\xb91\\\\xcaI8\\\\xfe+\\\\xd3\\\\xdbi\\\\xc6\\\\x83\\\\xa6yN\\\\xb2\\\\xdbg\\\\xa6\\\\xf07\\\\x00\\\\r\\\\x00\\\\x14\\\\x00\\\\x12\\\\x04\\\\x03\\\\x08\\\\x04\\\\x04\\\\x01\\\\x05\\\\x03\\\\x08\\\\x05\\\\x05\\\\x01\\\\x08\\\\x06\\\\x06\\\\x01\\\\x02\\\\x01\\\\x00\\\\x05\\\\x00\\\\x05\\\\x01\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x12\\\\x00\\\\x00\\\\x00\\\\x10\\\\x00\\\\x0e\\\\x00\\\\x0c\\\\x02h2\\\\x08http/1.1\\\\x00\\\\x0b\\\\x00\\\\x02\\\\x01\\\\x00\\\\x00\\\\n\\\\x00\\\\n\\\\x00\\\\x08ZZ\\\\x00\\\\x1d\\\\x00\\\\x17\\\\x00\\\\x18\\\\x00\\\\x1b\\\\x00\\\\x03\\\\x02\\\\x00\\\\x02JJ\\\\x00\\\\x01\\\\x00\\\\x00\\\\x15\\\\x00`\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\\x00\\\'\')') ``` Traceback (most recent call last): File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/server.py", line 121, in handle root_layer() File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/modes/http_proxy.py", line 9, in __call__ layer() File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/protocol/tls.py", line 283, in __call__ layer() File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/protocol/http1.py", line 83, in __call__ layer() File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/protocol/http.py", line 188, in __call__ if not self._process_flow(flow): File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/protocol/http.py", line 260, in _process_flow return self.handle_regular_connect(f) File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/protocol/http.py", line 206, in handle_regular_connect layer() File "/Users/gunson/.pyenv/versions/3.7.2/envs/cross-tester/lib/python3.7/site-packages/mitmproxy/proxy/protocol/tls.py", line 265, in __call__ self._client_hello.alpn_protocols or AttributeError: 'NoneType' object has no attribute 'alpn_protocols' mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy 127.0.0.1:65290: clientdisconnect ``` It had same crash on 4.0.4 or 5 beta
What happens if you capture the handshake in Wireshark? Can you share a PCAP? This doesn't look like valid TLS. ![image](https://user-images.githubusercontent.com/11094461/69846015-0080a480-12b6-11ea-97af-80085ba0092f.png) I filtered tcp.port where the client hello error occur. [crash.pcapng.zip](https://github.com/mitmproxy/mitmproxy/files/3903873/crash.pcapng.zip) Unfortunately I do not have an Android 10 device, but I tested with Firefox and curl - without seeing any problems. I can fix the bug in mitmproxy so it doesn't crash any more - but the TLS ClientHello parsing error comes straight from the Kaitai definition. @ujjwal96 any ideas about this one?
2019-11-30T11:44:08
mitmproxy/mitmproxy
3,745
mitmproxy__mitmproxy-3745
[ "3722" ]
a58b8c9cdbfea7bb77d36e646ce14e6f4f1d64f3
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 @@ -3,10 +3,10 @@ import urwid -import mitmproxy.tools.console.master # noqa +import mitmproxy.tools.console.master # noqa +from mitmproxy.tools.console import commandexecutor from mitmproxy.tools.console import common from mitmproxy.tools.console import signals -from mitmproxy.tools.console import commandexecutor from mitmproxy.tools.console.commander import commander @@ -57,6 +57,7 @@ def sig_message(self, sender, message, expire=1): def cb(*args): if w == self._w: self.clear() + signals.call_in.send(seconds=expire, callback=cb) def prep_prompt(self, p): @@ -105,7 +106,13 @@ def sig_prompt_command(self, sender, partial: str = "", cursor: Optional[int] = ) if cursor is not None: self._w.cbuf.cursor = cursor - self.prompting = commandexecutor.CommandExecutor(self.master) + self.prompting = self.execute_command + + def execute_command(self, txt): + if txt.strip(): + self.master.commands.call("commands.history.add", txt) + execute = commandexecutor.CommandExecutor(self.master) + execute(txt) def sig_prompt_onekey(self, sender, prompt, keys, callback, args=()): """ @@ -140,7 +147,6 @@ def keypress(self, size, k): elif k == "enter": text = self._w.get_edit_text() self.prompt_execute(text) - self.master.commands.call("commands.history.add", text) else: if common.is_keypress(k): self._w.keypress(size, k) @@ -170,7 +176,7 @@ class StatusBar(urwid.WidgetWrap): keyctx = "" def __init__( - self, master: "mitmproxy.tools.console.master.ConsoleMaster" + self, master: "mitmproxy.tools.console.master.ConsoleMaster" ) -> None: self.master = master self.ib = urwid.WidgetWrap(urwid.Text(""))
Search inside a flow causes mitmproxy to crash #### Problem Description If you try to use the search feature inside a flow (by pressing '/') and type something to make a search, mitmproxy crashes. #### Steps to reproduce the behavior: 1. Open mitmproxy and make a few requests 2. Selct one of the flows in the main screen and open it (by pressing Enter) 3. In the flow, press `/` and type something and then press Enter 4. Notice that mitmproxy crashes #### System Information $ mitmproxy --version Mitmproxy: 5.0.0.dev (+413, commit 2f30981) Python: 3.7.3 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Linux-5.0.0-31-generic-x86_64-with-Ubuntu-19.04-disco
Can confirm, traceback: ``` Traceback (most recent call last): File "/Users/username/Projects/mitmproxy/mitmproxy/master.py", line 86, in run_loop loop() File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/main_loop.py", line 286, in run self._run() File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/main_loop.py", line 384, in _run self.event_loop.run() File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/main_loop.py", line 1484, in run reraise(*exc_info) File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/compat.py", line 58, in reraise raise value File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/raw_display.py", line 404, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/raw_display.py", line 502, in parse_input callback(processed, processed_codes) File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/main_loop.py", line 411, in _update self.process_input(keys) File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/main_loop.py", line 511, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/Users/username/Projects/mitmproxy/mitmproxy/tools/console/window.py", line 310, in keypress k = super().keypress(size, k) File "/Users/username/Envs/mitmproxy-0GFVzhJ3/lib/python3.7/site-packages/urwid/container.py", line 1119, in keypress return self.footer.keypress((maxcol,),key) File "/Users/username/Projects/mitmproxy/mitmproxy/tools/console/statusbar.py", line 198, in keypress return self.ab.keypress(*args, **kwargs) File "/Users/username/Projects/mitmproxy/mitmproxy/tools/console/statusbar.py", line 145, in keypress self.command_history.add_command(self._w.cbuf, True) AttributeError: 'Edit' object has no attribute 'cbuf' ``` ``` Mitmproxy: 5.0.0.dev (+444, commit bbb7eb6) Python: 3.7.4 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Darwin-18.7.0-x86_64-i386-64bit ``` @mhils Bug should be fixed in new pull request. By the way, i'm wondering why console GUI used, instead of more advanced like QT, or GTK? @peter-way I find it quite useful to be able to use mitmproxy GUI in machines I have SSH access on (keeping it running in a tmux session, for instance). Also, mitmweb interface should be the place to look for a greater "GUI-like" experience :)
2019-12-12T15:43:22
mitmproxy/mitmproxy
3,766
mitmproxy__mitmproxy-3766
[ "3765" ]
406f8acc9709e51822cd19f537406a688ee37920
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -81,7 +81,7 @@ "ruamel.yaml>=0.16,<0.17", "sortedcontainers>=2.1.0,<2.2", "tornado>=4.3,<7", - "urwid>=2.0.1,<2.1", + "urwid>=2.1.0,<2.2", "wsproto>=0.14.0,<0.15.0", "publicsuffix2>=2.20190812,<3", "zstandard>=0.11.0,<0.13.0",
AttributeError: 'tuple' object has no attribute 'find' #### Problem Description I tried to run successfully but when I hit ESC, below error displayed. #### Steps to reproduce the behavior: 1. Run `$ mitmproxy -p 9999 --mode socks5 --showhost` ``` Traceback (most recent call last): File "/Users/binhho/Documents/t-mobile/mitmproxy/mitmproxy/master.py", line 86, in run_loop loop() File "/Users/binhho/Documents/t-mobile/mitmproxy/venv/lib/python3.7/site-packages/urwid/main_loop.py", line 286, in run self._run() File "/Users/binhho/Documents/t-mobile/mitmproxy/venv/lib/python3.7/site-packages/urwid/main_loop.py", line 384, in _run self.event_loop.run() File "/Users/binhho/Documents/t-mobile/mitmproxy/venv/lib/python3.7/site-packages/urwid/main_loop.py", line 1484, in run reraise(*exc_info) File "/Users/binhho/Documents/t-mobile/mitmproxy/venv/lib/python3.7/site-packages/urwid/compat.py", line 58, in reraise raise value File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/Users/binhho/Documents/t-mobile/mitmproxy/venv/lib/python3.7/site-packages/urwid/raw_display.py", line 404, in <lambda> event_loop, callback, self.get_available_raw_input()) File "/Users/binhho/Documents/t-mobile/mitmproxy/venv/lib/python3.7/site-packages/urwid/raw_display.py", line 475, in parse_input codes, wait_for_more) File "/Users/binhho/Documents/t-mobile/mitmproxy/venv/lib/python3.7/site-packages/urwid/escape.py", line 387, in process_keyqueue if run[0] == "esc" or run[0].find("meta ") >= 0: AttributeError: 'tuple' object has no attribute 'find' ``` #### System Information Paste the output of "mitmproxy --version" here. ``` Mitmproxy: 6.0.0.dev (+17, commit 406f8ac) Python: 3.7.5 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Darwin-19.2.0-x86_64-i386-64bit ```
This should be fixed in the recent urwid version 2.1.0: https://github.com/urwid/urwid/pull/304 We need to test and fix incompatibilities with this new dependency.
2019-12-31T10:04:25
mitmproxy/mitmproxy
3,779
mitmproxy__mitmproxy-3779
[ "3778" ]
184384af57e81bce09469e2fefe6dbb134eda6ce
diff --git a/mitmproxy/tools/console/common.py b/mitmproxy/tools/console/common.py --- a/mitmproxy/tools/console/common.py +++ b/mitmproxy/tools/console/common.py @@ -543,7 +543,7 @@ def format_flow(f, focus, extended=False, hostheader=False, cols=False, layout=' duration = None if f.response.timestamp_end and f.request.timestamp_start: - duration = f.response.timestamp_end - f.request.timestamp_start + duration = max([f.response.timestamp_end - f.request.timestamp_start, 0]) d.update(dict( resp_code=f.response.status_code,
"ValueError: math domain error" in table mode when displaying a server replay flow #### Problem Description `mitmproxy` crashes when it tries to display a replayed flows in a table mode. With active server replay, flow's duration is negative, so `math.log2` receives a negative value which is illegal. Traceback: ``` File "mitmproxy/master.py", line 86, in run_loop File "site-packages/urwid/main_loop.py", line 286, in run File "site-packages/urwid/main_loop.py", line 384, in _run File "site-packages/urwid/main_loop.py", line 1484, in run File "site-packages/urwid/compat.py", line 58, in reraise File "asyncio/events.py", line 88, in _run File "site-packages/urwid/main_loop.py", line 1443, in faux_idle_callback File "site-packages/urwid/main_loop.py", line 572, in entering_idle File "site-packages/urwid/main_loop.py", line 586, in draw_screen File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/container.py", line 1086, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/decoration.py", line 226, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/container.py", line 1086, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/listbox.py", line 471, in render File "site-packages/urwid/listbox.py", line 356, in calculate_visible File "mitmproxy/tools/console/flowlist.py", line 57, in get_focus File "mitmproxy/tools/console/flowlist.py", line 12, in __init__ File "mitmproxy/tools/console/flowlist.py", line 22, in get_text File "mitmproxy/tools/console/common.py", line 561, in format_flow File "mitmproxy/tools/console/common.py", line 488, in raw_format_table ValueError: math domain error ``` #### Steps to reproduce the behavior: 1. Start `mitmproxy` with table layout active 2. Make an HTTP call 3. Add the call to server replay 4. Make the call again #### System Information ``` Mitmproxy: 5.0.1 binary Python: 3.7.5 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-5.0.0-38-generic-x86_64-with-debian-buster-sid ```
Should we set it to 0, whenever `f.response.timestamp_end < f.request.timestamp_start` ? The number will be incorrect, but it won't crash anymore. > Should we set it to 0, whenever f.response.timestamp_end < f.request.timestamp_start ? It is an option, because seeing times like `-321075ms` is kind of misleading. Another one is just take maximum of 0 and flow's duration, because the problem code is used for getting color. I would be fine with either setting this to 0 in the console code or with refreshing the `timestamp_` attributes in the server playback addons. PRs welcome! 😃
2020-01-10T17:11:59
mitmproxy/mitmproxy
3,801
mitmproxy__mitmproxy-3801
[ "3794" ]
66fe6530631bae9371401f5a86cf4be797107e5c
diff --git a/mitmproxy/command.py b/mitmproxy/command.py --- a/mitmproxy/command.py +++ b/mitmproxy/command.py @@ -149,9 +149,10 @@ def collect_commands(self, addon): if not i.startswith("__"): o = getattr(addon, i) try: - is_command = hasattr(o, "command_name") + # hasattr is not enough, see https://github.com/mitmproxy/mitmproxy/issues/3794 + is_command = isinstance(getattr(o, "command_name", None), str) except Exception: - pass # hasattr may raise if o implements __getattr__. + pass # getattr may raise if o implements __getattr__. else: if is_command: try:
Addons: TypeError: unexpected object #### Problem Description I'm trying to set up [zerorpc](https://github.com/0rpc/zerorpc-python) inside an addon. It does work but mitmproxy spits out a stack trace when it encounters a reference to an instance of `zerorpc.Client` anywhere. #### Steps to reproduce the behavior: 1. `pipx inject mitmproxy zerorpc` 2. `mitmdump --scripts addon.py` ```python import zerorpc class MyAddon: def __init__(self): self.rpc = zerorpc.Client() addons = [ MyAddon() ] ``` ``` Addon error: Traceback (most recent call last): File "/home/alex/.local/pipx/venvs/mitmproxy/lib/python3.7/site-packages/mitmproxy/addonmanager.py", line 42, in safecall yield File "/home/alex/.local/pipx/venvs/mitmproxy/lib/python3.7/site-packages/mitmproxy/addons/script.py", line 102, in loadscript ctx.master.addons.register(ns) File "/home/alex/.local/pipx/venvs/mitmproxy/lib/python3.7/site-packages/mitmproxy/addonmanager.py", line 161, in register self.master.commands.collect_commands(a) File "/home/alex/.local/pipx/venvs/mitmproxy/lib/python3.7/site-packages/mitmproxy/command.py", line 158, in collect_commands self.add(o.command_name, o) File "/home/alex/.local/pipx/venvs/mitmproxy/lib/python3.7/site-packages/mitmproxy/command.py", line 165, in add self.commands[path] = Command(self, path, func) File "/home/alex/.local/pipx/venvs/mitmproxy/lib/python3.7/site-packages/mitmproxy/command.py", line 64, in __init__ self.signature = inspect.signature(self.func) File "/usr/lib/python3.7/inspect.py", line 3083, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped) File "/usr/lib/python3.7/inspect.py", line 2833, in from_callable follow_wrapper_chains=follow_wrapped) File "/usr/lib/python3.7/inspect.py", line 2246, in _signature_from_callable 'attribute'.format(sig)) TypeError: unexpected object <function ClientBase.__getattr__.<locals>.<lambda> at 0x7f66616d0b00> in __signature__ attribute ``` the absolute minimal example is this, which does not error when run directly outside of mitmproxy but does when used as an addon ```python import zerorpc c = zerorpc.Client() ``` I don't know enough Python to understand the underlying issue. I assume there is nothing wrong with zerorpc but with the assumptions mitmproxy makes about stuff that addons expose? #### System Information ``` Mitmproxy: 5.0.1 Python: 3.7.5 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-5.3.0-26-generic-x86_64-with-Ubuntu-19.10-eoan ```
For now I've worked around it by lazily creating an instance. I can't even use `rpcPlease()` inside `__init__`. Even without assigning it to a variable. This works: ```python import mitmproxy.websocket import zerorpc _rpc = None def rpcPlease(): global _rpc if _rpc is None: _rpc = zerorpc.Client() _rpc.connect("tcp://127.0.0.1:4242") return _rpc class MyAddon: # def __init__(self): # print(rpcPlease().hello("__init__")) def websocket_message(self, flow: mitmproxy.websocket.WebSocketFlow): rpc = rpcPlease() print(rpc.hello("websocket_message")) addons = [ MyAddon() ] ``` this does not (I only uncommented the two lines) ```python import mitmproxy.websocket import zerorpc _rpc = None def rpcPlease(): global _rpc if _rpc is None: _rpc = zerorpc.Client() _rpc.connect("tcp://127.0.0.1:4242") return _rpc class MyAddon: def __init__(self): print(rpcPlease().hello("__init__")) def websocket_message(self, flow: mitmproxy.websocket.WebSocketFlow): rpc = rpcPlease() print(rpc.hello("websocket_message")) addons = [ MyAddon() ] ``` Since zerorpc is not thread safe I've switched to gRPC and the issue is gone (I can have a global channel and stub instance without any problem). So maybe it was triggering an edge case that nobody else will ever encounter again. I'll leave this open and let you decide to close it. Maybe if one of you peeks at the stack trace above they'll know right away what was happening.
2020-01-27T21:44:50
mitmproxy/mitmproxy
3,815
mitmproxy__mitmproxy-3815
[ "3780", "3780" ]
c16b4887875bcdecdf18355f28347a48ba4297fd
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 @@ -87,6 +87,18 @@ class Http2Layer(base.Layer): # mypy type hints client_conn: connections.ClientConnection = None + class H2ConnLogger: + def __init__(self, name, log): + self.name = name + self.log = log + + def debug(self, fmtstr, *args): + msg = "H2Conn {}: {}".format(self.name, fmtstr % args) + self.log(msg, "debug") + + def trace(self, fmtstr, *args): + pass + def __init__(self, ctx, mode: str) -> None: super().__init__(ctx) self.mode = mode @@ -98,7 +110,8 @@ def __init__(self, ctx, mode: str) -> None: client_side=False, header_encoding=False, validate_outbound_headers=False, - validate_inbound_headers=False) + validate_inbound_headers=False, + logger=self.H2ConnLogger("client", self.log)) self.connections[self.client_conn] = SafeH2Connection(self.client_conn, config=config) def _initiate_server_conn(self): @@ -107,7 +120,8 @@ def _initiate_server_conn(self): client_side=True, header_encoding=False, validate_outbound_headers=False, - validate_inbound_headers=False) + validate_inbound_headers=False, + logger=self.H2ConnLogger("server", self.log)) self.connections[self.server_conn] = SafeH2Connection(self.server_conn, config=config) self.connections[self.server_conn].initiate_connection() self.server_conn.send(self.connections[self.server_conn].data_to_send()) @@ -195,10 +209,12 @@ def _handle_data_received(self, eid, event, source_conn): else: self.streams[eid].data_queue.put(event.data) self.streams[eid].queued_data_length += len(event.data) - self.connections[source_conn].safe_acknowledge_received_data( - event.flow_controlled_length, - event.stream_id - ) + + # always acknowledge receved data with a WINDOW_UPDATE frame + self.connections[source_conn].safe_acknowledge_received_data( + event.flow_controlled_length, + event.stream_id + ) return True def _handle_stream_ended(self, eid): @@ -461,7 +477,7 @@ def raise_zombie(self, pre_command=None): # pragma: no cover if self.zombie is not None or connection_closed: if pre_command is not None: pre_command() - raise exceptions.Http2ZombieException("Connection already dead") + raise exceptions.Http2ZombieException("Connection or stream already dead: {}, {}".format(self.zombie, connection_closed)) @detect_zombie_stream def read_request_headers(self, flow): @@ -643,7 +659,8 @@ def run(self): try: layer() except exceptions.Http2ZombieException: # pragma: no cover - pass + # zombies can be safely terminated - no need to kill them twice + return except exceptions.ProtocolException as e: # pragma: no cover self.log(repr(e), "info") except exceptions.SetServerNotAllowedException as e: # pragma: no cover diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -68,7 +68,7 @@ "click>=7.0,<8", "cryptography>=2.1.4,<2.5", "flask>=1.1.1,<1.2", - "h2>=3.0.1,<4", + "h2>=3.2.0,<4", "hyperframe>=5.1.0,<6", "kaitaistruct>=0.7,<0.9", "ldap3>=2.6.1,<2.7",
ProtocolException("Error in HTTP connection: Http2ZombieException('Connection already dead')") #### Problem Description The thumbnails on YouTube don't load after navigating around the page. I'm not sure what exactly is happening, it seems to be related to HTTP 2? See the attached video. Sorry for the video being such a hot mess. During recording it didn't happen after the first navigation (of course, why would it) and it took a moment to be reproducible. When I opened the image in a new tab it still didn't load. The second time I [alt+enter]ed it into a new tab. In dev tools the requests appear as `(pending)`. So mitmproxy never tells Chrome that the request failed? ![Selection_561](https://user-images.githubusercontent.com/679144/72176316-69dbf300-33de-11ea-80e2-09fe60047eb7.png) #### Steps to reproduce the behavior: 1. Start `mitmdump` 2. Open Chromium 3. Browse to www.youtube.com 4. Click on a video 5. Go back to the front page by clicking on the logo 6. Most thumbnails will not load (you might need to repeat 4+5). I assume it is related to the error in the title. No amount of waiting makes them load. Now the question is: is YouTube or Chromium doing something funny or is it mitmproxy that has the issue? #### System Information ``` Mitmproxy: 5.0.1 Python: 3.7.5 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-5.3.0-26-generic-x86_64-with-Ubuntu-19.10-eoan ``` #### Attachments video: http://www.prinzhorn.me/mitmproxy/screencast.mp4 video of me hovering the thumbnails: http://www.prinzhorn.me/mitmproxy/screencast-hover.mp4 dump: http://www.prinzhorn.me/mitmproxy/youtube ProtocolException("Error in HTTP connection: Http2ZombieException('Connection already dead')") #### Problem Description The thumbnails on YouTube don't load after navigating around the page. I'm not sure what exactly is happening, it seems to be related to HTTP 2? See the attached video. Sorry for the video being such a hot mess. During recording it didn't happen after the first navigation (of course, why would it) and it took a moment to be reproducible. When I opened the image in a new tab it still didn't load. The second time I [alt+enter]ed it into a new tab. In dev tools the requests appear as `(pending)`. So mitmproxy never tells Chrome that the request failed? ![Selection_561](https://user-images.githubusercontent.com/679144/72176316-69dbf300-33de-11ea-80e2-09fe60047eb7.png) #### Steps to reproduce the behavior: 1. Start `mitmdump` 2. Open Chromium 3. Browse to www.youtube.com 4. Click on a video 5. Go back to the front page by clicking on the logo 6. Most thumbnails will not load (you might need to repeat 4+5). I assume it is related to the error in the title. No amount of waiting makes them load. Now the question is: is YouTube or Chromium doing something funny or is it mitmproxy that has the issue? #### System Information ``` Mitmproxy: 5.0.1 Python: 3.7.5 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-5.3.0-26-generic-x86_64-with-Ubuntu-19.10-eoan ``` #### Attachments video: http://www.prinzhorn.me/mitmproxy/screencast.mp4 video of me hovering the thumbnails: http://www.prinzhorn.me/mitmproxy/screencast-hover.mp4 dump: http://www.prinzhorn.me/mitmproxy/youtube
Thanks for the extensive write-up! The obvious workaround is to disable HTTP2 in mitmproxy, but we want to get that fixed anyways of course. /cc @Kriechi (somewhat refs #1775) I can reproduce the issue with Firefox on macOS as well. This problem seems related to RESET_STREAM, when the browser sends a request, but a few milliseconds sends a RESET for that same stream. The server already responded with the full body. Then something stalls/breaks/blocks - I haven't found that last bit yet... Found the underlying problem - it is in one of our dependencies that take care of the low-level heavy-lifting for HTTP/2. https://github.com/python-hyper/hyper-h2/issues/1210 Thanks for the extensive write-up! The obvious workaround is to disable HTTP2 in mitmproxy, but we want to get that fixed anyways of course. /cc @Kriechi (somewhat refs #1775) I can reproduce the issue with Firefox on macOS as well. This problem seems related to RESET_STREAM, when the browser sends a request, but a few milliseconds sends a RESET for that same stream. The server already responded with the full body. Then something stalls/breaks/blocks - I haven't found that last bit yet... Found the underlying problem - it is in one of our dependencies that take care of the low-level heavy-lifting for HTTP/2. https://github.com/python-hyper/hyper-h2/issues/1210
2020-02-09T10:08:53
mitmproxy/mitmproxy
3,839
mitmproxy__mitmproxy-3839
[ "3833" ]
6d3b8c9716a274fdcc72c4dc9a841f2e8fa4d1e9
diff --git a/mitmproxy/net/http/headers.py b/mitmproxy/net/http/headers.py --- a/mitmproxy/net/http/headers.py +++ b/mitmproxy/net/http/headers.py @@ -162,8 +162,12 @@ def replace(self, pattern, repl, flags=0, count=0): pattern = re.compile(pattern, flags) replacements = 0 flag_count = count > 0 + count_reached = False fields = [] for name, value in self.fields: + if count_reached: + fields.append((name, value)) + continue line, n = pattern.subn(repl, name + b": " + value, count=count) try: name, value = line.split(b": ", 1) @@ -173,10 +177,12 @@ def replace(self, pattern, repl, flags=0, count=0): pass else: replacements += n + fields.append((name, value)) if flag_count: count -= n if count == 0: - break + count_reached = True + continue fields.append((name, value)) self.fields = tuple(fields) return replacements
diff --git a/test/mitmproxy/net/http/test_headers.py b/test/mitmproxy/net/http/test_headers.py --- a/test/mitmproxy/net/http/test_headers.py +++ b/test/mitmproxy/net/http/test_headers.py @@ -88,6 +88,8 @@ def test_replace_with_count(self): headers = Headers(Host="foobarfoo.com", Accept="foo/bar") replacements = headers.replace("foo", "bar", count=1) assert replacements == 1 + assert headers["Host"] == "barbarfoo.com" + assert headers["Accept"] == "foo/bar" def test_parse_content_type():
Headers replace bug when count is set #### Problem Description Headers matching for replace are fully removed, if count=1 #### Steps to reproduce the behavior: 1. create header instance: `headers = Headers(host='foo.com', referrer='foo.com')` 2. replace `foo` with `bar` and `count=1`: `headers.replace('foo', 'bar', count=1)` 3. result is empty headers: `Headers[]` ``` >>> headers = Headers(host='foo.com', referrer='foo.com') >>> headers.replace('foo', 'bar', count=1) 1 >>> headers Headers[] ``` #### System Information Mitmproxy: 5.0.1 Python: 3.7.6 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Darwin-19.3.0-x86_64-i386-64bit
Thanks for providing super easy steps to reproduce this! :smiley: I'll try to fix it.
2020-02-28T11:19:06
mitmproxy/mitmproxy
3,881
mitmproxy__mitmproxy-3881
[ "3880" ]
3046a628fd0b719ff587eac5f5fd6965cd5eac89
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 @@ -160,10 +160,10 @@ def connect(self): """ if not self.server_conn.address: raise exceptions.ProtocolException("Cannot connect to server, no server address given.") - self.log("serverconnect", "debug", [repr(self.server_conn.address)]) - self.channel.ask("serverconnect", self.server_conn) try: self.server_conn.connect() + self.log("serverconnect", "debug", [repr(self.server_conn.address)]) + self.channel.ask("serverconnect", self.server_conn) except exceptions.TcpException as e: raise exceptions.ProtocolException( "Server connection to {} failed: {}".format(
ServerConnection.ip_address is not populated inside `serverconnect` event #### Problem Description Inside the `serverconnect` event the `ip_address` property is not populated, it is `None`. The `address` property is correctly populated. Since the connection is open I would expect the IP address to be known and the property to be available. #### Steps to reproduce the behavior: `mitmdump --scripts conn.py` ```python def serverconnect(conn): print('-------connect--------------') print(conn.id) print(conn.address) print(conn.ip_address) print('-------/connect--------------') def serverdisconnect(conn): print('----------disconnect-----------') print(conn.id) print(conn.address) print(conn.ip_address) print('----------/disconnect-----------') ``` Output ``` -------connect-------------- ab301a58-2366-4025-bab9-77c2bdfe74e6 ('prinzhorn.it', 80) None -------/connect-------------- ----------disconnect----------- ab301a58-2366-4025-bab9-77c2bdfe74e6 ('prinzhorn.it', 80) ('87.98.150.101', 80) ----------/disconnect----------- ``` #### System Information ``` Mitmproxy: 5.0.1 Python: 3.7.5 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-5.3.0-45-generic-x86_64-with-Ubuntu-19.10-eoan ```
I assume this is the place https://github.com/mitmproxy/mitmproxy/blob/3046a628fd0b719ff587eac5f5fd6965cd5eac89/mitmproxy/proxy/protocol/base.py#L164-L166 If this is expected behavior then the docs need to be updated. It says > Mitmproxy **has** connected to a server. `conn.connected()` is `False` in both cases. Either it needs to be `True` inside `serverconnect` or `True` inside `serverdisconnect`. It is not symmetrical right now. https://github.com/mitmproxy/mitmproxy/blob/3046a628fd0b719ff587eac5f5fd6965cd5eac89/mitmproxy/proxy/protocol/base.py#L148-L149
2020-04-02T09:20:32
mitmproxy/mitmproxy
3,929
mitmproxy__mitmproxy-3929
[ "3920" ]
2774928319b706d8b6f85919f8811776342986c9
diff --git a/mitmproxy/contentviews/json.py b/mitmproxy/contentviews/json.py --- a/mitmproxy/contentviews/json.py +++ b/mitmproxy/contentviews/json.py @@ -1,16 +1,39 @@ +import re import json -from typing import Optional + +import typing from mitmproxy.contentviews import base +PARSE_ERROR = object() + -def pretty_json(s: bytes) -> Optional[bytes]: +def parse_json(s: bytes) -> typing.Any: try: - p = json.loads(s.decode('utf-8')) + return json.loads(s.decode('utf-8')) except ValueError: - return None - pretty = json.dumps(p, sort_keys=True, indent=4, ensure_ascii=False) - return pretty.encode("utf8", "strict") + return PARSE_ERROR + + +def format_json(data: typing.Any) -> typing.Iterator[base.TViewLine]: + encoder = json.JSONEncoder(indent=4, sort_keys=True, ensure_ascii=False) + current_line: base.TViewLine = [] + for chunk in encoder.iterencode(data): + if "\n" in chunk: + rest_of_last_line, chunk = chunk.split("\n", maxsplit=1) + # rest_of_last_line is a delimiter such as , or [ + current_line.append(('text', rest_of_last_line)) + yield current_line + current_line = [] + if re.match(r'\s*"', chunk): + current_line.append(('json_string', chunk)) + elif re.match(r'\s*\d', chunk): + current_line.append(('json_number', chunk)) + elif re.match(r'\s*(true|null|false)', chunk): + current_line.append(('json_boolean', chunk)) + else: + current_line.append(('text', chunk)) + yield current_line class ViewJSON(base.View): @@ -22,6 +45,6 @@ class ViewJSON(base.View): ] def __call__(self, data, **metadata): - pj = pretty_json(data) - if pj: - return "JSON", base.format_text(pj) + data = parse_json(data) + if data is not PARSE_ERROR: + return "JSON", format_json(data) diff --git a/mitmproxy/tools/console/palettes.py b/mitmproxy/tools/console/palettes.py --- a/mitmproxy/tools/console/palettes.py +++ b/mitmproxy/tools/console/palettes.py @@ -35,6 +35,9 @@ class Palette: # Hex view 'offset', + # JSON view + 'json_string', 'json_number', 'json_boolean', + # Grid Editor 'focusfield', 'focusfield_error', 'field_error', 'editfield', @@ -170,6 +173,11 @@ class LowDark(Palette): # Hex view offset = ('dark cyan', 'default'), + # JSON view + json_string = ('dark blue', 'default'), + json_number = ('light magenta', 'default'), + json_boolean = ('dark magenta', 'default'), + # Grid Editor focusfield = ('black', 'light gray'), focusfield_error = ('dark red', 'light gray'), @@ -270,6 +278,11 @@ class LowLight(Palette): # Hex view offset = ('dark blue', 'default'), + # JSON view + json_string = ('dark blue', 'default'), + json_number = ('light magenta', 'default'), + json_boolean = ('dark magenta', 'default'), + # Grid Editor focusfield = ('black', 'light gray'), focusfield_error = ('dark red', 'light gray'), @@ -380,6 +393,11 @@ class SolarizedLight(LowLight): # Hex view offset = (sol_cyan, 'default'), + # JSON view + json_string = (sol_cyan, 'default'), + json_number = (sol_blue, 'default'), + json_boolean = (sol_magenta, 'default'), + # Grid Editor focusfield = (sol_base00, sol_base2), focusfield_error = (sol_red, sol_base2), @@ -454,6 +472,11 @@ class SolarizedDark(LowDark): # Hex view offset = (sol_cyan, 'default'), + # JSON view + json_string = (sol_cyan, 'default'), + json_number = (sol_blue, 'default'), + json_boolean = (sol_magenta, 'default'), + # Grid Editor focusfield = (sol_base0, sol_base02), focusfield_error = (sol_red, sol_base02),
diff --git a/test/mitmproxy/contentviews/test_json.py b/test/mitmproxy/contentviews/test_json.py --- a/test/mitmproxy/contentviews/test_json.py +++ b/test/mitmproxy/contentviews/test_json.py @@ -1,16 +1,43 @@ +from hypothesis import given +from hypothesis.strategies import binary + from mitmproxy.contentviews import json from . import full_eval -def test_pretty_json(): - assert json.pretty_json(b'{"foo": 1}') - assert not json.pretty_json(b"moo") - assert json.pretty_json(b'{"foo" : "\xe4\xb8\x96\xe7\x95\x8c"}') # utf8 with chinese characters - assert not json.pretty_json(b'{"foo" : "\xFF"}') +def test_parse_json(): + assert json.parse_json(b'{"foo": 1}') + assert json.parse_json(b'null') is None + assert json.parse_json(b"moo") is json.PARSE_ERROR + assert json.parse_json(b'{"foo" : "\xe4\xb8\x96\xe7\x95\x8c"}') # utf8 with chinese characters + assert json.parse_json(b'{"foo" : "\xFF"}') is json.PARSE_ERROR + + +def test_format_json(): + assert list(json.format_json({ + "data": [ + "str", + 42, + True, + False, + None, + {}, + [] + ] + })) def test_view_json(): v = full_eval(json.ViewJSON()) + assert v(b"null") assert v(b"{}") assert not v(b"{") assert v(b"[1, 2, 3, 4, 5]") + assert v(b'{"foo" : 3}') + assert v(b'{"foo": true, "nullvalue": null}') + + +@given(binary()) +def test_view_json_doesnt_crash(data): + v = full_eval(json.ViewJSON()) + v(data)
Colorize JSON Contentview I use mitmweb or mitmproxy to debug webhooks call to my api, often these webhooks are full of useful JSON data. So I think a JSON syntax coloration is a key feature for a proxy like that. May be I don't have it enabled or whatever and this feature is already implemented but not enabled by default ?
That sounds like a useful feature suggestion! We do have support for syntax highlighting for contentviews (see the hex view for example), if someone would extend the JSON view to do that, that'd be great! 😃 https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/hex.py https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/json.py
2020-04-12T11:47:37
mitmproxy/mitmproxy
3,930
mitmproxy__mitmproxy-3930
[ "3748" ]
30645fa1ac6fa828bda390383abee7c04f20206f
diff --git a/mitmproxy/version.py b/mitmproxy/version.py --- a/mitmproxy/version.py +++ b/mitmproxy/version.py @@ -2,7 +2,7 @@ import subprocess import sys -VERSION = "6.0.0.dev" +VERSION = "5.1.0" PATHOD = "pathod " + VERSION MITMPROXY = "mitmproxy " + VERSION diff --git a/release/cibuild.py b/release/cibuild.py --- a/release/cibuild.py +++ b/release/cibuild.py @@ -356,15 +356,6 @@ def build_docker_image(be: BuildEnviron): # pragma: no cover "--file", "release/docker/Dockerfile", "." ]) - subprocess.check_call([ - "docker", - "build", - "--tag", be.docker_tag + "-ARMv7", - "--build-arg", "WHEEL_MITMPROXY={}".format(whl), - "--build-arg", "WHEEL_BASENAME_MITMPROXY={}".format(os.path.basename(whl)), - "--file", "release/docker/DockerfileARMv7", - "." - ]) def build_pyinstaller(be: BuildEnviron): # pragma: no cover @@ -569,11 +560,10 @@ def upload(): # pragma: no cover "-u", be.docker_username, "-p", be.docker_password, ]) - for variant in ["", "-ARMv7"]: - subprocess.check_call(["docker", "push", be.docker_tag + variant]) - if be.is_prod_release: - subprocess.check_call(["docker", "tag", be.docker_tag + variant, "mitmproxy/mitmproxy:latest" + variant]) - subprocess.check_call(["docker", "push", "mitmproxy/mitmproxy:latest" + variant]) + subprocess.check_call(["docker", "push", be.docker_tag]) + if be.is_prod_release: + subprocess.check_call(["docker", "tag", be.docker_tag, "mitmproxy/mitmproxy:latest"]) + subprocess.check_call(["docker", "push", "mitmproxy/mitmproxy:latest"]) if __name__ == "__main__": # pragma: no cover
iOS 13.3: Certificate installation instructions need improvement #### Problem Description After installing profile and activating it, Safari still shows websites as "not trusted" and apps show "network error" #### Steps to reproduce the behavior: 1. Configure wifi to use mitmproxy 2. Install and activate profile from mitm.it 3. Navigate anywhere in Safari refs https://github.com/mitmproxy/mitmproxy/issues/3649 (added EKU) and #3647 #### System Information Paste the output of "mitmproxy --version" here. ``` Mitmproxy: 5.0.0 Python: 3.7.5 OpenSSL: OpenSSL 1.1.1d 10 Sep 2019 Platform: Darwin-19.2.0-x86_64-i386-64bit ```
Yes, this should work in 5.0. Did you delete your ~/.mitmproxy folder and then reinstall the certificate on your device (https://docs.mitmproxy.org/stable/concepts-certificates/#installing-the-mitmproxy-ca-certificate-manually)? > Did you delete your ~/.mitmproxy folder and then reinstall the certificate on your device (https://docs.mitmproxy.org/stable/concepts-certificates/#installing-the-mitmproxy-ca-certificate-manually)? I have only started working with mitmproxy just now, so no old settings. I will try explicit certificate trust on top of the profile installation and see if that works. I finally found out how to run all of this. ### My settings ``` bash mitmproxy --version Mitmproxy: 5.0.0 Python: 3.7.5 OpenSSL: OpenSSL 1.1.1d 10 Sep 2019 Platform: Darwin-18.7.0-x86_64-i386-64bit ``` iPhone XS (current latest OS). ### Step-by-step #### Macbook 1) `brew install mitmproxy` 2) run `mitmweb` for web interface 3) in new Terminal window run `ifconfig` to find out your laptop local IP address (probably starts with `192.168. ... `) #### iPhone 1) Open settings -> Wi-Fi -> "your Wi-Fi network" -> Configure Proxy 2) Insert into "Server" your local laptop's IP and default port "8080" 3) In Safari open website 'mitm.it' and install sertificate 4) Open Settings -> General -> Profiles -> mitmproxy -> Verify the sertificate And now everything will be `Trusted` and `Awesome`! I've found that I need to add one more step. After following 1-4, I needed to trust the certificate as root certificate. This is apparently not achieved by installing the profile alone: Goto Settings -> General -> Info -> Certificate Trust -> Mitmproxy and enabled "Trusted Root" (German screenshot below): ![IMG_5C7034BD2845-1](https://user-images.githubusercontent.com/184815/71243714-30e5bc80-2311-11ea-8f54-b67e1e132a49.jpeg) Is this the expected behaviour? Add to docs? Otherwise good to close! Thanks @ohld and @andig! Looks like we need to mention this more prominently. We currently have it at https://docs.mitmproxy.org/stable/concepts-certificates/#installing-the-mitmproxy-ca-certificate-manually and on mitm.it: https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/onboardingapp/templates/index.html#L30. If you two could think about ways how you would not have missed it, I'd be super happy to merge a PR! 😃 I was looking here https://docs.mitmproxy.org/stable/concepts-certificates/ which seems to suggest that on iOS I need to only install the profile according to `Quick setup`. `Installing the mitmproxy CA certificate manually`(the next chapter's name) is kinda misleading. I was not going for a manual install but *still* needed to accept the certificate at root. Imho, at least for iOS, that needs to be added to the `Quick Setup` chapter, too? @andig: Didn't that display instructions for the extra steps on mitm.it? If it did, do we need to make them more prominent? Here's what I'm seeing: ![IMG_0329](https://user-images.githubusercontent.com/184815/71350645-00e92400-2572-11ea-902e-40515c00c8a1.png) ![IMG_0330](https://user-images.githubusercontent.com/184815/71350649-05154180-2572-11ea-9734-e69b018745aa.png) All information is there. It's more that- once the profile is installed- I immediately moved over to install the profile and never returned to read the remaining instructions. Only suggestion I could make is to put a fat additional disclaimer on https://docs.mitmproxy.org/stable/concepts-certificates/#quick-setup, maybe something like: > Click on the relevant icon, follow the setup instructions for the platform you’re on and you are good to go. **NOTE**: after clicking the relevant icon, additional installation steps are required. Make sure to fully read and follow instructions specific to your platform. Maybe put everything in **bold**. I feel highlighting these more might help. Also having this issue, removed ~/.mitmproxy on my system, then reinstalled certs/profile/enabled trusted root on ios 13.3 ``` Mitmproxy: 5.0.0 Python: 3.7.5 OpenSSL: OpenSSL 1.1.1d 10 Sep 2019 Platform: Darwin-19.2.0-x86_64-i386-64bit ``` Edit: Definitely an issue with the IOS update, Burp proxy doesn't seem to work as well. @andig: Thanks for sharing the screenshots! `mitm.it` lives at https://github.com/mitmproxy/mitmproxy/tree/master/mitmproxy/addons/onboardingapp. I'd be more than happy to merge a PR that improves the user experience here in some way. Some ideas: 1. We should definitely add a much more prominent "more steps needed" alert (red text?) for iOS so that the "Full Trust" instructions aren't overlooked. 2. We could also display more platform-specific icons, and then only show the platform, specific instructions. _Windows_, _Linux_, _macOS_, _iOS_, _Android_, _Firefox_, and _other_ would probably be a good start. Most of that should already be there, it's just a bit cluttered at the moment. 3. We could also do some User-Agent sniffing to highlight the correct choice for the given platform. Might be more of a gimmick than a useful feature. yep dev Sit on I'm still having a related issue. I used mitm.it to install the cert and switch the setting on for Full Trust. After doing this, I will see some https traffic, but large amounts are traffic are missing. I'm using it to validate that scripts like Google Tag Manager or Google Analytics are running and none of the network requests are coming over. Is anyone else experiencing limited network requests? This is happening for both ios and macos. Android will collect all data (I'm using the same site for everything) > This is happening for both ios and macos. On macOS, I was setting the proxy in firefox for http and I should have set for both http and https. For ios (13.3), is there an option to set a proxy for https explicitly? I was researching and something for Charles came up. They have an extra step at the end to enable server-side. https://benoitpasquier.com/charles-ssl-proxy-ios/#enable-ssl-proxy-on-charles Is anything like this needed for mitm? The same proxy session is collecting HTTPS on Android and now macOS browser. So I don't think it's a mitm configuration issue unless there's a setting specific to ios that I'm missing. This might be the issue: [](https://support.apple.com/en-us/HT210176) It appears Apple will not trust certificates that do not have a validity period of 825 days or fewer. The mitmproxy certificiate expires in three years. @fjord66: Only the root CA does, which is permitted under Apple's policy I believe. The leaf certs currently have a validity of two years. @mhils in certs.py I changed the DEFAULT_EXP to: DEFAULT_EXP = 63072000 and it worked to meet the new requirements Hi there! I have the next issue with current master << Cannot establish TLS with client (sni: fishkaapp.net): TlsException("SSL handshake error: SysCallError(-1, 'Unexpected EOF')",) This can be reproduced just for specific applications inside the device. For Safari and Chrome mitmproxy works good. **System Information** Mitmproxy: 6.0.0.dev (+126, commit 4d6886a) Python: 3.6.9 OpenSSL: OpenSSL 1.1.1f 31 Mar 2020 Platform: Linux-5.3.0-45-generic-x86_64-with-Ubuntu-18.04-bionic iOS 13.3.1 Is the app using certificate pinning? This looks like the same error you see when apps are using certificate pinning @fjord66 I think you are right. It looks like this! Just checked it - cert pinning was the issue :( > @mhils in certs.py I changed the DEFAULT_EXP to: DEFAULT_EXP = 63072000 and it worked to meet the new requirements This is working for me too! All https hits coming through. thanks! @fjord66 and @MichaelStadtmiller: I am not on macOS, which makes testing a bit difficult. If I understand you correctly, you also need the Root CA certificate (the one in ~/.mitmproxy) to be valid for less than 825 days (DEFAULT_EXP)? It is not sufficient to have a leaf certificate (the certificate which mitmproxy generates on-the-fly during execution for the actual interception, signed by the root CA) with a reduced lifetime (DEFAULT_EXP_DUMMY_CERT)? That is correct I just took the most recent master branch of mitmproxy, wiped my local CA, restarted mitmproxy, installed the profile with CA in an iPhone with iOS 13.4, enabled the full-trust setting for this mitmproxy CA. I am able to browse all websites as usual and mitmproxy is tracking all flows as expected. My iOS Safari is properly showing the Lock symbol in the address bar. I can inspect and intercept flows as expected.
2020-04-12T20:51:29
mitmproxy/mitmproxy
3,938
mitmproxy__mitmproxy-3938
[ "3904" ]
bfb8da4b1c5f1422b4a9031d1e3e77d40552208c
diff --git a/mitmproxy/tools/_main.py b/mitmproxy/tools/_main.py --- a/mitmproxy/tools/_main.py +++ b/mitmproxy/tools/_main.py @@ -110,6 +110,8 @@ def run( master.commands.dump() sys.exit(0) if extra: + if(args.filter_args): + master.log.info(f"Only processing flows that match \"{' & '.join(args.filter_args)}\"") opts.update(**extra(args)) loop = asyncio.get_event_loop()
Mitmdump option error #### Problem Description When passing random arguments to mitmdump it doesn't show any error. Steps to reproduce the behavior: 1. Type mitmdump abc It doesn't show any flow after that just clientconnect and clientdisconnect on requests but no error about wrong argument. Mitmproxy show this kind of error. I am not sure this is supposed to behave like this or this is a bug. #### System Information Paste the output of "mitmproxy --version" here. Mitmproxy: 6.0.0.dev (+116, commit 7791410) Python: 3.7.5 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-5.3.0-kali2-amd64-x86_64-with-debian-kali-rolling
They don't have the same signature. `mitmdump` has `[filter]`. I assume that's what confuses you (I didn't know either, just noticed it). Request sth. like `www.example.com/abc` and you'll see it because of the /abc ``` $ mitmproxy --help usage: mitmproxy [options] ``` ``` $ mitmdump --help usage: mitmdump [options] [filter] positional arguments: filter_args Filter expression, equivalent to setting both the view_filter and save_stream_filter options. ``` > I assume that's what confuses you (I didn't know either, just noticed it). Request sth. like `www.example.com/abc` and you'll see it because of the /abc > Well you are right, this confuses me and thanks for clearing this up,I think for spaces filter is apply to url as request to www.example.com/abc is shown on `mitmdump abc` And for more spaces i guess it check for content after slashes as in `mitmdump example abc mod` request to www.example.com/abc/mod is shown. I think a example of this should be added to docs for better understanding. It is a filter expression, see https://docs.mitmproxy.org/stable/concepts-filters/ > Strings with no operators are matched against the request URL. What I don't understand is why `mitmdump "foo bar"` will match "/foo/bar". Maybe that's something I don't know about Python-style regex @mhils ? Shouldn't the space be taken literal? I think what can be done better is that if `[filter]` is provided then mitmdump could show the user what `view_filter` this results in. At least in `verbose` mode. > I think a example of this should be added to docs for better understanding. I think `--help` should contain some examples in general Do you have any suggestions what exactly you would change to make things more clear? What what you add to the docs? > Strings with no operators are matched against the request URL. > I think i miss that line. > I think --help should contain some examples in general > Yeah it can be applied instead of docs. For the docs i think we can add some example in https://docs.mitmproxy.org/stable/tools-mitmdump/ about url filtering with or without "~u" and if multiple spaces is legit then also add some more info in https://docs.mitmproxy.org/stable/concepts-filters/ Related: https://github.com/mitmproxy/mitmproxy/issues/3142 I think there's room for improvement in multiple places. Thank you for bringing it up. Yeah, let's see @mhils thought about that. > What I don't understand is why mitmdump "foo bar" will match "/foo/bar". Maybe that's something I don't know about Python-style regex @mhils ? Shouldn't the space be taken literal? mitmweb actually has the best interface here which explains it: ![image](https://user-images.githubusercontent.com/1019198/78750493-a339e580-7970-11ea-934e-454c36760b54.png) The explanation is generated by the JS reimplementation in [web/src/js/filt/filt.peg](https://github.com/mitmproxy/mitmproxy/blob/master/web/src/js/filt/filt.peg)). Would be nice if we had the same in the console somewhere. FWIW, the behavior is also mentioned in the docs at https://docs.mitmproxy.org/stable/concepts-filters/: - Strings with no operators are matched against the request URL. - The default binary operator is &. That explanation is obviously super cryptic for everyone who doesn't know filters. 😄 > For the docs i think we can add some example in https://docs.mitmproxy.org/stable/tools-mitmdump/ about url filtering with or without "~u" and if multiple spaces is legit then also add some more info in https://docs.mitmproxy.org/stable/concepts-filters/ I feel that it might be more intuitive to just make it a regular option (like --filter) instead of parsing argv. What do you two think? >I feel that it might be more intuitive to just make it a regular option (like --filter) instead of parsing argv. What do you two think? > You mean for url filter add an extra option like `mitmdump [options] --urlfilter [expression]` Yeah it world be great and as @Prinzhorn suggested we can add some more info in `--help` about this. @mhils @Prinzhorn any update on this. Looking at the implementation the argv handling does a bit more than what I initially thought: https://github.com/mitmproxy/mitmproxy/blob/bfb8da4b1c5f1422b4a9031d1e3e77d40552208c/mitmproxy/tools/_main.py#L154-L162 Maybe we just add a `f"Only processing flows that match {v!r}"` message to mitmdump and be done with it. If someone feels like it we can move the mitmweb filter explainer to Python.
2020-04-15T06:07:34
mitmproxy/mitmproxy
3,982
mitmproxy__mitmproxy-3982
[ "3981", "3981" ]
7fdcbb09e6034ab1f76724965cfdf45f3d775129
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -106,7 +106,10 @@ def dummy_cert(privkey, cacert, commonname, sans, organization): cert.gmtime_adj_notBefore(-3600 * 48) cert.gmtime_adj_notAfter(DEFAULT_EXP_DUMMY_CERT) cert.set_issuer(cacert.get_subject()) - if commonname is not None and len(commonname) < 64: + is_valid_commonname = ( + commonname is not None and len(commonname) < 64 + ) + if is_valid_commonname: cert.get_subject().CN = commonname if organization is not None: cert.get_subject().O = organization @@ -114,7 +117,13 @@ def dummy_cert(privkey, cacert, commonname, sans, organization): if ss: cert.set_version(2) cert.add_extensions( - [OpenSSL.crypto.X509Extension(b"subjectAltName", False, ss)]) + [OpenSSL.crypto.X509Extension( + b"subjectAltName", + # RFC 5280 §4.2.1.6: subjectAltName is critical if subject is empty. + not is_valid_commonname, + ss + )] + ) cert.add_extensions([ OpenSSL.crypto.X509Extension( b"extendedKeyUsage",
incomplete certificate generated by mitmproxy #### Problem Description A clear and concise description of what the bug is. When using mitm proxy to fetch the following resource: > https://document-storage-production-dot-remarkable-production.appspot.com/document-storage/json/2/docs I get the following exception: ``` Caused by: java.security.cert.CertificateParsingException: X.509 Certificate is incomplete: SubjectAlternativeName extension MUST be marked critical when subject field is empty at java.base/sun.security.x509.X509CertInfo.verifyCert(X509CertInfo.java:751) ``` I don't know why, but the Subject of the certificate generated by mitmproxy does not get set to anything in this case. If I force the SubjectAlternativeName extension to be critical by changing the source code as follows, the problem disappears and the certificate is accepted by Java: ```diff (venv) sebster@eeyore:~/Work/mitmproxy$ git diff diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py index a37d29bc..cbedc1fd 100644 --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -114,7 +114,7 @@ def dummy_cert(privkey, cacert, commonname, sans, organization): if ss: cert.set_version(2) cert.add_extensions( - [OpenSSL.crypto.X509Extension(b"subjectAltName", False, ss)]) + [OpenSSL.crypto.X509Extension(b"subjectAltName", True, ss)]) cert.add_extensions([ OpenSSL.crypto.X509Extension( b"extendedKeyUsage", ``` #### Steps to reproduce the behavior: 1. Attempt to fetch the above resource with mitmproxy from a Java client (OpenJDK 11.0.1) #### System Information Mitmproxy: 6.0.0.dev (+44, commit 7fdcbb0) Python: 3.6.9 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-5.3.0-51-generic-x86_64-with-Ubuntu-18.04-bionic incomplete certificate generated by mitmproxy #### Problem Description A clear and concise description of what the bug is. When using mitm proxy to fetch the following resource: > https://document-storage-production-dot-remarkable-production.appspot.com/document-storage/json/2/docs I get the following exception: ``` Caused by: java.security.cert.CertificateParsingException: X.509 Certificate is incomplete: SubjectAlternativeName extension MUST be marked critical when subject field is empty at java.base/sun.security.x509.X509CertInfo.verifyCert(X509CertInfo.java:751) ``` I don't know why, but the Subject of the certificate generated by mitmproxy does not get set to anything in this case. If I force the SubjectAlternativeName extension to be critical by changing the source code as follows, the problem disappears and the certificate is accepted by Java: ```diff (venv) sebster@eeyore:~/Work/mitmproxy$ git diff diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py index a37d29bc..cbedc1fd 100644 --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -114,7 +114,7 @@ def dummy_cert(privkey, cacert, commonname, sans, organization): if ss: cert.set_version(2) cert.add_extensions( - [OpenSSL.crypto.X509Extension(b"subjectAltName", False, ss)]) + [OpenSSL.crypto.X509Extension(b"subjectAltName", True, ss)]) cert.add_extensions([ OpenSSL.crypto.X509Extension( b"extendedKeyUsage", ``` #### Steps to reproduce the behavior: 1. Attempt to fetch the above resource with mitmproxy from a Java client (OpenJDK 11.0.1) #### System Information Mitmproxy: 6.0.0.dev (+44, commit 7fdcbb0) Python: 3.6.9 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-5.3.0-51-generic-x86_64-with-Ubuntu-18.04-bionic
2020-05-05T18:42:39
mitmproxy/mitmproxy
3,992
mitmproxy__mitmproxy-3992
[ "3986" ]
3372b77e93c7adf98f6d067bf7bb01ded42054c0
diff --git a/mitmproxy/websocket.py b/mitmproxy/websocket.py --- a/mitmproxy/websocket.py +++ b/mitmproxy/websocket.py @@ -17,7 +17,7 @@ class WebSocketMessage(serializable.Serializable): """ def __init__( - self, type: int, from_client: bool, content: bytes, timestamp: Optional[int]=None, killed: bool=False + self, type: int, from_client: bool, content: bytes, timestamp: Optional[float]=None, killed: bool=False ) -> None: self.type = Opcode(type) # type: ignore """indicates either TEXT or BINARY (from wsproto.frame_protocol.Opcode).""" @@ -25,7 +25,7 @@ def __init__( """True if this messages was sent by the client.""" self.content = content """A byte-string representing the content of this message.""" - self.timestamp: int = timestamp or int(time.time()) + self.timestamp: float = timestamp or time.time() """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."""
Increase WebSocket message timestamp precision #### Is your feature request related to a problem? Please describe. Timestamps for WebSocket messages are rounded to whole seconds. For at least some protocols or analyses, a higher precision may be useful or even necessary for productive use; one example is measuring the performance impact of mitmproxy. #### Describe the solution you'd like Avoid converting the timestamp to an integer and use a float instead: https://github.com/mitmproxy/mitmproxy/blob/7fdcbb09e6034ab1f76724965cfdf45f3d775129/mitmproxy/websocket.py#L28 Basic support for higher-precision timestamps seems to be as simple as changing the type of `WebSocketMessage.timestamp` from `int` to `float` and dropping the `int()` call around `time.time()`. I'm not sure if more is needed e.g. to ensure backward compatibility, but I was able to read a previous dump just fine with that modification (which makes sense since integers in the relevant range are strictly a subset of double-precision floats). #### Describe alternatives you've considered If keeping the `timestamp` an `int` is unavoidable, the Linux approach of storing the microseconds in a second integer (between 0 and 999999, inclusive) could be used. I don't think this is a good idea though. #### Additional context None
Thanks! You are absolutely right, this should just be a float. Happy to accept a PR that fixes this. :)
2020-05-09T13:29:36
mitmproxy/mitmproxy
3,996
mitmproxy__mitmproxy-3996
[ "848" ]
3372b77e93c7adf98f6d067bf7bb01ded42054c0
diff --git a/mitmproxy/options.py b/mitmproxy/options.py --- a/mitmproxy/options.py +++ b/mitmproxy/options.py @@ -181,5 +181,11 @@ def __init__(self, **kwargs) -> None: TLS key size for certificates and CA. """ ) + self.add_option( + "relax_http_form_validation", bool, False, + """ + Disable HTTP form validation. + """ + ) self.update(**kwargs) 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 @@ -267,10 +267,12 @@ def _process_flow(self, f): self.send_error_response(400, msg) return False - validate_request_form(self.mode, request) + if not self.config.options.relax_http_form_validation: + validate_request_form(self.mode, request) self.channel.ask("requestheaders", f) # Re-validate request form in case the user has changed something. - validate_request_form(self.mode, request) + if not self.config.options.relax_http_form_validation: + validate_request_form(self.mode, request) if request.headers.get("expect", "").lower() == "100-continue": # TODO: We may have to use send_response_headers for HTTP2
Requesting complete URL over https proxy results in "Invalid request scheme: https" ##### Steps to reproduce the problem: 1. Set up an HTTPS mitmproxy 2. Run the following (minimized) code against it: ``` python import httplib conn = httplib.HTTPSConnection('<your proxy IP>',<your proxy port>) conn.set_tunnel('www.google.com',443) conn.request('GET','https://www.google.com:443/') resp = conn.getresponse() print resp.read() ``` ##### What is the expected behavior? ``` html <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>301 Moved</TITLE></HEAD><BODY> <H1>301 Moved</H1> The document has moved <A HREF="http://www.google.com/">here</A>. </BODY></HTML> ``` ##### What went wrong? ``` html <html> <head> <title>400 Bad Request</title> </head> <body>HttpException('Invalid request scheme: https',)</body> </html> ``` ##### Any other comments? I believe it's caused by a combination of https://github.com/mitmproxy/mitmproxy/blob/master/libmproxy/protocol/http.py#L544-L545 and https://github.com/mitmproxy/mitmproxy/blob/master/libmproxy/protocol/http.py#L502-L503. Indeed, if you modify my `GET` request above to ask for just `/` instead of `https://www.google.com:443/`, everything works fine. I'm not sure if it's sensible to support absolute-form requests over https tunnels, but I'm getting this behavior in real code (boto for python AWS) so I don't think it's very a contrived situation. --- mitmproxy version: 0.14.0
I attempted a naive patch to remove the check for `http` and the check right below it for expected form but that just led to a 400 error elsewhere. Oh, never mind. Adjusting the two checks to allow for my situation makes the whole thing work beautifully. Not sure if it messes with other mitmproxy internal invariants though. It actually seems to mess with the way the request goes through to the final destination though, and breaks AWS's request signing after it makes its way through the proxy. Thanks for investigating this! > I'm not sure if it's sensible to support absolute-form requests over https tunnels Unfortunately, it's part of the spec that every HTTP1 request can be in absolute-form. I haven't seen it in practice before this though. For us, it's a nontrivial UI/UX problem. Cosider an initial CONNECT request ``` http CONNECT 10.0.0.1 HTTP/1.1 ``` followed by this HTTP request: ``` http GET http://example.com/ HTTP/1.1 Content-Length: 42 [...] ``` We now have two different destinations - which one should we show to the user? There's no guarantee that the host in the second request isn't fake and just showing "example.org" while we actually transmit data to $evilip is bad. However, we shouldn't omit the destination from the URL in the UI either. Our current workaround is to require relative-form requests if we already have a known destination. We also catch a lot of user errors this way (e.g. people who run mitmproxy in transparent mode while configuring it on the client as well). There's also our "smart" `request.host` attribute for scripts which would need to deal with this issue as well. TL;DR: Yes, we _should_ support this as it's perfectly valid HTTP. On the other hand, we'd need to make quite a few tradeoffs for a feature that is rarely used :confused: > It actually seems to mess with the way the request goes through to the final destination though, and breaks AWS's request signing after it makes its way through the proxy. I _think_ this is caused by [libmproxy/protocol/http.py#L497-L503](https://github.com/mitmproxy/mitmproxy/blob/b5d5e56fdb32717ab8f4c99c4f31c56df46afa91/libmproxy/protocol/http.py#L497-L503), which implicitly assumes relative-form requests. One way to approach this problem would be to make the HTTP protocol support absolute-form transparent requests and add a `--relax-http` switch to mitmproxy which disables the validation part. Any better ideas? > We now have two different destinations - which one should we show to the user? Isn't that already a problem with standard HTTP? I can already connect to one of the IPs backing google.com and send it a request for a page on microsoft.com. The `Host` header also adds a third potential axis of variability there. Does the proxy layer really add much more? > Any better ideas? That seems fine, although I still don't quite see what part of the code is breaking my request signature, even if we removed the sanity checks. Oh, I see from your link: ``` # Setting request.host also updates the host header, which we want to preserve ``` > Isn't that already a problem with standard HTTP? It is - it also affects mitmproxy's transparent mode the same way. Our issue is that we can't distinguish if the client is now talking to a proxy (which looks the same way) or just sends an absolute-form request for no reason. Even worse, an attacker may use this to actively misguide an analyst. For a mitmproxy user, it should always be clear where requests are going to, so we decided to just fail in these ambigious situations. For the host header, it's a bit different in the sense as the presence of the Host header cannot be mistaken for a proxy request. Thus, you can pass `--host` to mitmproxy and we will use that as display source in transparent mode. > That seems fine, although I still don't quite see what part of the code is breaking my request signature, even if we removed the sanity checks. We fill in (in the absolute-form case: overwrite) attributes of the request from the connection metadata in transparent mode: [libmproxy/protocol/http.py#L497-L503](https://github.com/mitmproxy/mitmproxy/blob/b5d5e56fdb32717ab8f4c99c4f31c56df46afa91/libmproxy/protocol/http.py#L497-L503) > We fill in (in the absolute-form case: overwrite) attributes of the request from the connection metadata in transparent mode: libmproxy/protocol/http.py#L497-L503 Yeah, sorry, I meant I couldn't tell within that what specifically was breaking boto's AWS signature. I think it's not actually any of the headers, but the path in my request that might be slightly different. In the code I linked, `host`, `port` and `scheme` get modified - these three are attributes of the request line. In particular, `scheme` should very likely be just `http` not `https` in your case. Changing the scheme [here](https://github.com/mitmproxy/mitmproxy/blob/b5d5e56fdb32717ab8f4c99c4f31c56df46afa91/libmproxy/protocol/http.py#L503) to `http` now just results in 502 Bad Gateway responses to all my client requests. For debugging, I'd recommend adding breakpoints / `print(http1.assemble_request(request))` statements in `Http1Layer.read_request`/`Http1Layer.send_request`. I can't look into this myself right now, sorry. No problem, I don't have much time right now either but I'll try to take a look a bit later. Thanks for all your help! @copumpkin Is this still an issue with mitmproxy 0.16? I seem to be hitting the same issue trying to use mitmproxy with Google Drive Sync Client: This is the error messages in the Google Drive Sync Client logs: ``` 2016-07-05 11:34:46,880 +1000 WARNING pid=62177 140735142223872:MainThread proxy_manager.pyo:420 using env setting for proxy: 'https://XXX.XXX.XXX.XXX:8080' 2016-07-05 11:34:46,881 +1000 INFO pid=62177 140735142223872:MainThread service.pyo:132 Creating singleton service instance of '<class 'common.net.dapper.DapperService'>' 2016-07-05 11:34:46,881 +1000 INFO pid=62177 140735142223872:MainThread sync_http_client.pyo:235 Tunneling connection to accounts.google.com:443 through 104.196.40.101:8080. 2016-07-05 11:34:48,660 +1000 ERROR pid=62177 140735142223872:MainThread oauth.pyo:138 OAuth failure. Error on request. Response 400. <html> <head> <title>400 Bad Request</title> </head> <body>HttpException('Invalid request scheme: https',)</body> </html> 2016-07-05 11:34:48,661 +1000 ERROR pid=62177 140735142223872:MainThread fatal_exceptions.pyo:55 Ignoring non-fatal error: Unauthorized: OAuth failure. Error on request. Response 400. <html> <head> <title>400 Bad Request</title> </head> <body>HttpException('Invalid request scheme: https',)</body> </html>, Traceback: File "common/auth/oauth.pyo", line 136, in GetAuthToken File "common/auth/oauth.pyo", line 196, in _AuthorizeOAuth2Token File "common/auth/oauth2_token.pyo", line 143, in AcquireAccessToken File "common/auth/oauth2_token.pyo", line 199, in _SendRequest 2016-07-05 11:37:19,349 +1000 INFO pid=62177 140735142223872:MainThread service.pyo:132 Creating singleton service instance of '<class 'controls.selective_sync_stats.SelectiveSyncStatsTracker'>' 2016-07-05 11:37:19,395 +1000 INFO pid=62177 123145326632960:_LaunchSyncApp pause_manager.pyo:106 Adding pause reason USER 2016-07-05 11:37:19,419 +1000 INFO pid=62177 123145330839552:RunAsync-_PerformAsyncSignOutTasks-7 service.pyo:132 Creating singleton service instance of '<class 'common.telemetry.impression_logger_manager.ImpressionLoggerManager'>' 2016-07-05 11:37:19,428 +1000 INFO pid=62177 123145326632960:_LaunchSyncApp sync_app.pyo:2057 Sign out remove token success: True 2016-07-05 11:37:19,432 +1000 ERROR pid=62177 123145330839552:RunAsync-_PerformAsyncSignOutTasks-7 fatal_exceptions.pyo:55 Ignoring non-fatal error: ImpressionLoggerManagerStateError: Uploader not configured., Traceback: File "common/exception_utils.pyo", line 72, in SuppressExceptions File "common/threads/run_async.pyo", line 55, in ErrorHandler File "common/sync_app.pyo", line 1978, in _PerformAsyncSignOutTasks File "common/telemetry/impression_logger_manager.pyo", line 284, in UploadLogsIfEnabled 2016-07-05 11:37:19,434 +1000 INFO pid=62177 123145326632960:_LaunchSyncApp sync_app.pyo:1992 Stopping threads 2016-07-05 11:37:19,434 +1000 INFO pid=62177 123145326632960:_LaunchSyncApp thread_manager.pyo:116 Stop was called 2016-07-05 11:37:19,434 +1000 INFO pid=62177 123145326632960:_LaunchSyncApp thread_manager.pyo:253 Asking <RunFunctionThread(_LaunchSyncApp, started 123145326632960)> with tid 123145326632960 to stop. 2016-07-05 11:37:19,435 +1000 INFO pid=62177 123145326632960:_LaunchSyncApp thread_manager.pyo:264 Stop completed successfully. 2016-07-05 11:37:19,437 +1000 INFO pid=62177 123145326632960:_LaunchSyncApp utils.pyo:226 set called on <common.utils.LoggingEvent object at 0x10fb9cd10> from: File "threading.pyo", line 783, in __bootstrap File "threading.pyo", line 810, in __bootstrap_inner File "common/threads/threads.pyo", line 93, in run File "threading.pyo", line 763, in run File "common/threads/threads.pyo", line 83, in AutoreleasePoolWrappedTarget File "common/sync_client_thread.pyo", line 50, in RunSyncClientThread File "common/sync_client_thread.pyo", line 326, in Run File "osx/mac_sync_app_controller.pyo", line 178, in _LaunchSyncApp File "common/sync_app.pyo", line 664, in LaunchThreads File "common/persistence/sqlite.pyo", line 127, in Wrapper File "common/sync_app.pyo", line 689, in _LaunchThreads File "common/sync_app.pyo", line 846, in _RunSetupAndSignIn File "common/sync_app.pyo", line 2061, in SignOut File "common/sync_app.pyo", line 1993, in _SignOutThreadManagerAndDropDatabases File "common/thread_manager.pyo", line 136, in StopThreadsAndWait File "common/thread_manager.pyo", line 124, in Stop File "common/thread_manager.pyo", line 391, in Stop File "common/utils.pyo", line 226, in set ``` @Kriechi Also, to clarify - yes, I believe this is still an issue in mitmproxy 0.16 - I tested against `HEAD`, and I hit this issue =(. (The latest version on Pypi is mitmproxy 0.17, right?) Just bumping - is this something you guys are working on =). Any idea of timeframe? (Cool if there's not, just trying to set my expectations). There have been some major changes regarding first-line format in mitmproxy. Is this still an issue, or has v1.0 solved it? To be honest, going through the thread here again: It seems we are dealing with a very uncommon use case. Only very recently did e.g. curl start to support HTTPS proxies. Or am I missing some context from the original problem here? This is still an issue I believe, and it's not related to HTTP**S** proxies. :-) If a client CONNECTs to a remote server and then sends an absolute-form request (e.g. `CONNECT http://example.com:80/`, then `GET http://example.com/foo`), we currently fail deliberately. This is because the host in the CONNECT request and the GET request do not necessarily have to be the same and we just have one `.host` attribute. Generally speaking, an unexpected first-line-format is most of the times a sign of misconfiguration (the RFC permits absolute form for all requests though). There are two things I'd love to see: 1. First, always accept requests in absolute-form going to the same host. For example, after `CONNECT example.com`, we should accept `GET http://example.com/foo`, but not `GET http://example.org/foo`. This would for example fix this issue. 2. Second, as you suggested, add a `--relax-http-form-validation` switch that disables the form enforcement. any update on this issue? Same issue when requesting in emacs here, using mitmproxy 4.0.1. `--relax-http-form-validation` whats the new version of this? This param doesnot work in the newest binary I would love to see a fix for this issue as well. The nodeJS axios library is fairly well known, and it allows requesting complete URLs. There are calls for axios buried under other utilities that implement sigV4 for AWS that it would be very nice to be able to consume and use through mitmproxy. Just hit this with Emacs 26.1 (url.el), mitmproxy 4.0.4, trying to debug magit/forge#55 with mitmproxy.
2020-05-12T04:17:02
mitmproxy/mitmproxy
4,036
mitmproxy__mitmproxy-4036
[ "3987" ]
31a6f60e4597b695d3ad03d7d98eb4fd6c4d5858
diff --git a/mitmproxy/version.py b/mitmproxy/version.py --- a/mitmproxy/version.py +++ b/mitmproxy/version.py @@ -20,6 +20,13 @@ def get_dev_version() -> str: here = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) try: + # Check that we're in the mitmproxy repository: https://github.com/mitmproxy/mitmproxy/issues/3987 + subprocess.run( + ['git', 'cat-file', '-t', 'cb0e3287090786fad566feb67ac07b8ef361b2c3'], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + cwd=here, + check=True) git_describe = subprocess.check_output( ['git', 'describe', '--tags', '--long'], stderr=subprocess.STDOUT,
Version detection mistakes an unrelated parent git repository as its own #### Problem Description I use <https://github.com/pyenv/pyenv> for Python version and venv management. It's generally installed as a `git clone` and keeps the actual installations and venvs in some deep directories beneath itself. So in a typical setup, you will have a clone of pyenv's repository in `~/.pyenv`, and then if you install mitmproxy in some venv managed by pyenv, its files end up in e.g. `~/.pyenv/versions/3.8.2/envs/mitmproxy/lib/python3.8/site-packages/mitmproxy/`. Because mitmproxy's version detection uses `git describe` and some parent of this directory (namely, `~/.pyenv`) is indeed a git repository, it thinks that this is a dev installation and includes that information in its version output if appropriate, i.e. if there were commits since the last tag in that repo. #### Steps to reproduce the behavior: Any git repository higher in the hierarchy than where mitmproxy's files are located would work, but a typical pyenv setup can be reproduced as follows: 1. Install pyenv at some commit that is not tagged. The example below is based on https://github.com/pyenv/pyenv/commit/a8ca63fcc0d6b470e2d5fc18fb85fad90efd4a59, which is two commits ahead of the previous tag v1.2.17. Further, install at least one Python version (I'll assume 3.8.2 below). The installation can be somewhat complicated as various dependencies are required for compiling Python, so I shall not give details about that here. [Here](https://github.com/pyenv/pyenv#installation)'s the starting point for instructions. 2. Install [pyenv-virtualenv](https://github.com/pyenv/pyenv-virtualenv) for virtual environment management; I believe this step is optional for this particular issue, but it greatly simplifies things when using pyenv normally and is a common setup. 3. Install mitmproxy in pyenv: `pyenv virtualenv 3.8.2 mitmproxy && pyenv shell mitmproxy && pip install mitmproxy` 4. ``` $ mitmproxy --version Mitmproxy: 5.1.1 (+2, commit a8ca63f) ``` I have not tried it, but it should be possible to reproduce the same issue by installing mitmproxy in a venv in a directory that is somewhere beneath a git repository. #### Possible solution The `GIT_CEILING_DIRECTORIES` environment variable can be used to limit how far up the directory tree `git` will recurse. For example, GIT_CEILING_DIRECTORIES="$(cd .. && pwd)" git describe would not recurse past the parent directory when attempting to find a git repository. Note that this has to contain absolute paths, so `GIT_CEILING_DIRECTORIES=../..` or similar will not work. However, even with the strictest `GIT_CEILING_DIRECTORIES` value imaginable, this still doesn't cover the case where the mitmproxy directory is directly inside some unrelated repository (e.g. if someone were to version-control their `site-packages` directory), since that's the structure used in the actual mitmproxy repository. #### System Information ``` $ mitmproxy --version Mitmproxy: 5.1.1 (+2, commit a8ca63f) Python: 3.8.2 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-5.6.0-1-amd64-x86_64-with-glibc2.29 ```
Thanks for the detailed report. I guess we could run ``` git cat-file -t cb0e3287090786fad566feb67ac07b8ef361b2c3 ``` to check if we are in the right repo. Ah, clever. Yes, that should work reliably.
2020-06-19T15:17:27
mitmproxy/mitmproxy
4,066
mitmproxy__mitmproxy-4066
[ "4059" ]
d52b17f2006559ecc4bb6d065e46009f10456c1c
diff --git a/mitmproxy/utils/typecheck.py b/mitmproxy/utils/typecheck.py --- a/mitmproxy/utils/typecheck.py +++ b/mitmproxy/utils/typecheck.py @@ -81,6 +81,8 @@ def typespec_to_str(typespec: typing.Any) -> str: t = 'optional str' elif typespec == typing.Sequence[str]: t = 'sequence of str' + elif typespec == typing.Optional[int]: + t = 'optional int' else: raise NotImplementedError return t
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 @@ -72,6 +72,7 @@ def test_typesec_to_str(): assert(typecheck.typespec_to_str(str)) == "str" assert(typecheck.typespec_to_str(typing.Sequence[str])) == "sequence of str" assert(typecheck.typespec_to_str(typing.Optional[str])) == "optional str" + assert(typecheck.typespec_to_str(typing.Optional[int])) == "optional int" with pytest.raises(NotImplementedError): typecheck.typespec_to_str(dict)
Mitmweb fails with addons/options-configure.py example. I am new to learn it, but i follow official [demo][1], it can't working? ```python Proxy server listening at http://*:8888 ERROR:tornado.application:Uncaught exception GET /options.json (127.0.0.1) HTTPServerRequest(protocol='http', host='127.0.0.1:8081', method='GET', uri='/options.json', version='HTTP/1.1', remote_ip='127.0.0.1') Traceback (most recent call last): File "c:\users\jekoie\appdata\local\programs\python\python37-32\lib\site-packages\tornado\web.py", line 1697, in _execute result = method(*self.path_args, **self.path_kwargs) File "c:\users\jekoie\appdata\local\programs\python\python37-32\lib\site-packages\mitmproxy\tools\web\app.py", line 453, in get self.write(optmanager.dump_dicts(self.master.options)) File "c:\users\jekoie\appdata\local\programs\python\python37-32\lib\site-packages\mitmproxy\optmanager.py", line 469, in dump_dicts t = typecheck.typespec_to_str(o.typespec) File "c:\users\jekoie\appdata\local\programs\python\python37-32\lib\site-packages\mitmproxy\utils\typecheck.py", line 85, in typespec_to_str raise NotImplementedError NotImplementedError ERROR:tornado.access:500 GET /options.json (127.0.0.1) 3.91ms ```` [1]: https://docs.mitmproxy.org/stable/addons-options/#handling-configuration-updates
Thanks for reporting this. It's is a bug in mitmweb only, mitmproxy and mitmdump are unaffected. Repro: ``` mitmweb -s examples/addons/options-configure.py ```
2020-07-05T01:35:20
mitmproxy/mitmproxy
4,067
mitmproxy__mitmproxy-4067
[ "4057" ]
49e10d7cc226c4fa78a126fbc8ad6eb2d2fcce0c
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -173,9 +173,7 @@ def expire(self, entry): self.expire_queue.append(entry) if len(self.expire_queue) > self.STORE_CAP: d = self.expire_queue.pop(0) - for k, v in list(self.certs.items()): - if v == d: - del self.certs[k] + self.certs = {k: v for k, v in self.certs.items() if v != d} @staticmethod def load_dhparam(path):
mitmproxy dictionary changed size during iteration #### Problem Description A clear and concise description of what the bug is. 在使用mitmproxy作为二级代理时,出现了错误。 flow.live.change_upstream_proxy_server((proxy, 8080)) #### Steps to reproduce the behavior: 1. mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/server.py", line 121, in handle root_layer() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/modes/http_proxy.py", line 23, in __call__ layer() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/tls.py", line 286, in __call__ layer() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/http1.py", line 83, in __call__ layer() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/http.py", line 188, in __call__ if not self._process_flow(flow): File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/http.py", line 262, in _process_flow return self.handle_upstream_connect(f) File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/http.py", line 236, in handle_upstream_connect return layer() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/http.py", line 87, in __call__ layer() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/tls.py", line 279, in __call__ self._establish_tls_with_client_and_server() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/tls.py", line 365, in _establish_tls_with_client_and_server self._establish_tls_with_client() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/tls.py", line 369, in _establish_tls_with_client cert, key, chain_file = self._find_cert() File "/usr/lib/python3.6/site-packages/mitmproxy/proxy/protocol/tls.py", line 501, in _find_cert return self.config.certstore.get_cert(host, list(sans)) File "/usr/lib/python3.6/site-packages/mitmproxy/certs.py", line 326, in get_cert self.expire(entry) File "/usr/lib/python3.6/site-packages/mitmproxy/certs.py", line 156, in expire for k, v in list(self.certs.items()): RuntimeError: dictionary changed size during iteration #### System Information Paste the output of "mitmproxy --version" here. Mitmproxy: 4.0.4 Python: 3.6.3 OpenSSL: OpenSSL 1.0.2o 27 Mar 2018 Platform: Linux-3.10.0-1062.el7.x86_64-with
Hi, how can reproduce this?
2020-07-05T13:41:42
mitmproxy/mitmproxy
4,068
mitmproxy__mitmproxy-4068
[ "4028" ]
51b9ee109ed232da978134974701b788c0a202f5
diff --git a/mitmproxy/net/tcp.py b/mitmproxy/net/tcp.py --- a/mitmproxy/net/tcp.py +++ b/mitmproxy/net/tcp.py @@ -125,7 +125,9 @@ def read(self, length): # underlying BIO could not satisfy the needs of SSL_read() to continue the # operation. In this case a call to SSL_get_error with the return value of # SSL_read() will yield SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. - if (time.time() - start) < self.o.gettimeout(): + # 300 is OpenSSL default timeout + timeout = self.o.gettimeout() or 300 + if (time.time() - start) < timeout: time.sleep(0.1) continue else:
Crash from comparison with None #### Problem Description I got this crash after leaving mitmproxy open for a few hours: ``` Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/server.py", line 121, in handle root_layer()-laptop ~]$ File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/modes/http_proxy.py", line 9, in __call__ layer()oking-laptop ~]$ File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/tls.py", line 285, in __call__ layer() File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http1.py", line 83, in __call__ layer() File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http.py", line 190, in __call__ if not self._process_flow(flow): File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http.py", line 262, in _process_flow return self.handle_regular_connect(f) File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http.py", line 208, in handle_regular_connect layer() File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/tls.py", line 285, in __call__ layer() File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http1.py", line 83, in __call__ layer() File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http.py", line 190, in __call__ if not self._process_flow(flow): File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http.py", line 244, in _process_flow request = self.read_request_headers(f) File "/usr/lib/python3.8/site-packages/mitmproxy/proxy/protocol/http1.py", line 15, in read_request_headers http1.read_request_head(self.client_conn.rfile) File "/usr/lib/python3.8/site-packages/mitmproxy/net/http/http1/read.py", line 54, in read_request_head form, method, scheme, host, port, path, http_version = _read_request_line(rfile) File "/usr/lib/python3.8/site-packages/mitmproxy/net/http/http1/read.py", line 245, in _read_request_line line = _get_first_line(rfile) File "/usr/lib/python3.8/site-packages/mitmproxy/net/http/http1/read.py", line 232, in _get_first_line line = rfile.readline() File "/usr/lib/python3.8/site-packages/mitmproxy/net/tcp.py", line 158, in readline ch = self.read(1) File "/usr/lib/python3.8/site-packages/mitmproxy/net/tcp.py", line 128, in read if (time.time() - start) < self.o.gettimeout(): TypeError: '<' not supported between instances of 'float' and 'NoneType' ``` I use mitmproxy almost every day and this is the first time it happens. #### Steps to reproduce the behavior: No clue. #### System Information Mitmproxy: 5.1.1 Python: 3.8.3 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-5.6.15-arch1-1-x86_64-with-glibc2.2.5
2020-07-07T13:56:02
mitmproxy/mitmproxy
4,080
mitmproxy__mitmproxy-4080
[ "4037" ]
2bbffef3e1b1494e1e833fa67f53f3f088600b97
diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py --- a/mitmproxy/addons/clientplayback.py +++ b/mitmproxy/addons/clientplayback.py @@ -180,7 +180,7 @@ def stop_replay(self) -> None: self.q.queue.clear() for f in lst: f.revert() - ctx.master.addons.trigger("update", lst) + ctx.master.addons.trigger("update", lst) ctx.log.alert("Client replay queue cleared.") @command.command("replay.client")
replay.client.stop crashes the client #### Problem Description Running replay.client.stop (with or without pending replays) will crash the client and will require a full restart. Versions: MacOS 10.15.5 (19F96) Python 3.7.7 (default, Mar 10 2020, 15:43:33) The same also occurred on Ubuntu 20.04. #### Steps to reproduce the behavior: 1. Launch mitmproxy with given version 2. Run :replay.client.stop 3. Whole client crashes #### System Information Mitmproxy: 5.1.1 Python: 3.7.7 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Darwin-19.5.0-x86_64-i386-64bit
Thanks for the straightforward repro! @mhils No worries. I'll see if I can get to it in the near future (still a newbie to open source though).
2020-07-12T07:59:02
mitmproxy/mitmproxy
4,089
mitmproxy__mitmproxy-4089
[ "3990" ]
2dfcb537f27f38fb3631af835784753a490cc414
diff --git a/mitmproxy/flowfilter.py b/mitmproxy/flowfilter.py --- a/mitmproxy/flowfilter.py +++ b/mitmproxy/flowfilter.py @@ -43,6 +43,7 @@ from mitmproxy import http from mitmproxy import tcp from mitmproxy import websocket +from mitmproxy.net import websockets as net_websockets def only(*types): @@ -104,11 +105,15 @@ def __call__(self, f): class FWebSocket(_Action): code = "websocket" - help = "Match WebSocket flows" + help = "Match WebSocket flows (and HTTP-WebSocket handshake flows)" - @only(websocket.WebSocketFlow) + @only(http.HTTPFlow, websocket.WebSocketFlow) def __call__(self, f): - return True + m = ( + (isinstance(f, http.HTTPFlow) and f.request and net_websockets.check_handshake(f.request.headers)) + or isinstance(f, websocket.WebSocketFlow) + ) + return m class FTCP(_Action): diff --git a/mitmproxy/master.py b/mitmproxy/master.py --- a/mitmproxy/master.py +++ b/mitmproxy/master.py @@ -152,10 +152,15 @@ async def load_flow(self, f): self.waiting_flows.append(f) if isinstance(f, websocket.WebSocketFlow): - hf = [hf for hf in self.waiting_flows if hf.id == f.metadata['websocket_handshake']][0] - f.handshake_flow = hf - self.waiting_flows.remove(hf) - self._change_reverse_host(f.handshake_flow) + hfs = [hf for hf in self.waiting_flows if hf.id == f.metadata['websocket_handshake']] + if hfs: + hf = hfs[0] + f.handshake_flow = hf + self.waiting_flows.remove(hf) + self._change_reverse_host(f.handshake_flow) + else: + # this will fail - but at least it will load the remaining flows + f.handshake_flow = http.HTTPFlow(None, None) f.reply = controller.DummyReply() for e, o in eventsequence.iterate(f):
diff --git a/test/mitmproxy/test_flowfilter.py b/test/mitmproxy/test_flowfilter.py --- a/test/mitmproxy/test_flowfilter.py +++ b/test/mitmproxy/test_flowfilter.py @@ -439,6 +439,17 @@ def test_websocket(self): assert not self.q("~tcp", f) assert not self.q("~http", f) + def test_handshake(self): + f = self.flow().handshake_flow + assert self.q("~websocket", f) + assert not self.q("~tcp", f) + assert self.q("~http", f) + + f = tflow.tflow() + assert not self.q("~websocket", f) + f = tflow.tflow(resp=True) + assert not self.q("~websocket", f) + def test_ferr(self): e = self.err() assert self.q("~e", e)
~websocket filter when reading from a file does not work #### Problem Description It appears that the `~websocket` filter, which is supposed to match all WebSocket flows per <https://docs.mitmproxy.org/stable/concepts-filters/>, does not match anything when reading from an existing dump. #### Steps to reproduce the behavior: 1. Capture WebSocket traffic: `mitmdump -w infile ~websocket` 2. Apply a filter of `~websocket`: `mitmdump -nr infile -w outfile ~websocket` The result is a non-empty `infile`, which contains the expected WebSocket messages, and an **empty** `outfile` even though they should contain the same data. In addition, I also noticed that `mitmdump -nr infile` produces no output whatsoever, even with `-v` to increase the verbosity. I'm aware that the UI does not properly support WebSocket (#1020), but I'd expect it to at least report that messages exist as it does during dumping (i.e. `127.0.0.1:57466 -> WebSocket 1 message -> URL` etc.). This does not happen when the initial capturing is done without a filter, i.e. those "message" log lines appear in that case. This might point at a more fundamental issue with reading back the WebSocket data than just the filtering. #### System Information ``` $ mitmproxy --version Mitmproxy: 5.1.1 (+2, commit a8ca63f) Python: 3.8.2 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-5.6.0-1-amd64-x86_64-with-glibc2.29 ``` (Regarding the version number, see #3987; this is a clean 5.1.1 installation.)
The HTTP-WebSocket handshake flow is missing from the dump file, which seems to cause a few missing internal links... I'll send a PR to fix this by also matching all HTTP-WebSocket handshake flows with the `~websocket` filter.
2020-07-16T15:47:57
mitmproxy/mitmproxy
4,177
mitmproxy__mitmproxy-4177
[ "4155" ]
0203202b898572bf33b32bca88aa1a80757966ea
diff --git a/mitmproxy/addons/intercept.py b/mitmproxy/addons/intercept.py --- a/mitmproxy/addons/intercept.py +++ b/mitmproxy/addons/intercept.py @@ -1,20 +1,18 @@ import typing -from mitmproxy import flowfilter +from mitmproxy import flow, flowfilter from mitmproxy import exceptions from mitmproxy import ctx class Intercept: - def __init__(self): - self.filt = None + filt: typing.Optional[flowfilter.TFilter] = None def load(self, loader): loader.add_option( "intercept_active", bool, False, "Intercept toggle" ) - loader.add_option( "intercept", typing.Optional[str], None, "Intercept filter expression." @@ -22,25 +20,29 @@ def load(self, loader): def configure(self, updated): if "intercept" in updated: - if not ctx.options.intercept: + if ctx.options.intercept: + self.filt = flowfilter.parse(ctx.options.intercept) + if not self.filt: + raise exceptions.OptionsError(f"Invalid interception filter: {ctx.options.intercept}") + ctx.options.intercept_active = True + else: self.filt = None ctx.options.intercept_active = False - return - self.filt = flowfilter.parse(ctx.options.intercept) - if not self.filt: - raise exceptions.OptionsError( - "Invalid interception filter: %s" % ctx.options.intercept - ) - ctx.options.intercept_active = True - - def process_flow(self, f): - if self.filt: - should_intercept = all([ - self.filt(f), - not f.is_replay == "request", - ]) - if should_intercept and ctx.options.intercept_active: - f.intercept() + + def should_intercept(self, f: flow.Flow) -> bool: + return bool( + ctx.options.intercept_active + and self.filt + and self.filt(f) + and not f.is_replay + ) + + def process_flow(self, f: flow.Flow) -> None: + if self.should_intercept(f): + assert f.reply + if f.reply.state != "start": + return ctx.log.debug("Cannot intercept request that is already taken by another addon.") + f.intercept() # Handlers @@ -51,5 +53,4 @@ def response(self, f): self.process_flow(f) def tcp_message(self, f): - if self.filt and ctx.options.intercept_active: - f.intercept() + self.process_flow(f)
diff --git a/test/mitmproxy/addons/test_intercept.py b/test/mitmproxy/addons/test_intercept.py --- a/test/mitmproxy/addons/test_intercept.py +++ b/test/mitmproxy/addons/test_intercept.py @@ -43,12 +43,31 @@ def test_simple(): tctx.cycle(r, f) assert f.intercepted - tctx.configure(r, intercept_active=False) + +def test_tcp(): + r = intercept.Intercept() + with taddons.context(r) as tctx: + tctx.configure(r, intercept="~tcp") f = tflow.ttcpflow() tctx.cycle(r, f) - assert not f.intercepted + assert f.intercepted - tctx.configure(r, intercept_active=True) + tctx.configure(r, intercept_active=False) f = tflow.ttcpflow() tctx.cycle(r, f) + assert not f.intercepted + + +def test_already_taken(): + r = intercept.Intercept() + with taddons.context(r) as tctx: + tctx.configure(r, intercept="~q") + + f = tflow.tflow() + tctx.invoke(r, "request", f) assert f.intercepted + + f = tflow.tflow() + f.reply.take() + tctx.invoke(r, "request", f) + assert not f.intercepted
Cannot intercept ASGI requests ``` error: Addon error: Traceback (most recent call last): File "/home/martin/mitmproxy/mitmproxy/addons/intercept.py", line 48, in request self.process_flow(f) File "/home/martin/mitmproxy/mitmproxy/addons/intercept.py", line 43, in process_flow f.intercept() File "/home/martin/mitmproxy/mitmproxy/flow.py", line 172, in intercept self.reply.take() File "/home/martin/mitmproxy/mitmproxy/controller.py", line 92, in take "Reply is {}, but expected it to be start.".format(self.state) mitmproxy.exceptions.ControlException: Reply is taken, but expected it to be start. ``` _Originally posted by @mplattner in https://github.com/mitmproxy/mitmproxy/pull/4147#issuecomment-674060804_
2020-08-27T09:09:33
mitmproxy/mitmproxy
4,179
mitmproxy__mitmproxy-4179
[ "4021" ]
72dd56799492f44ff7cf3065f3038f609e317913
diff --git a/mitmproxy/utils/typecheck.py b/mitmproxy/utils/typecheck.py --- a/mitmproxy/utils/typecheck.py +++ b/mitmproxy/utils/typecheck.py @@ -39,7 +39,7 @@ def check_option_type(name: str, value: typing.Any, typeinfo: Type) -> None: typename = str(typeinfo) - if typename.startswith("typing.Union"): + if typename.startswith("typing.Union") or typename.startswith("typing.Optional"): for T in union_types(typeinfo): try: check_option_type(name, value, T)
TypeError: Subscripted generics cannot be used with class and instance checks under python 3.9.0b1 #### Problem Description Running mitmproxy 5.1.1 under python 3.9.0b1 fails with `TypeError: Subscripted generics cannot be used with class and instance checks`. The test suite fails as well with hundreds of ERROR and FAILED tests. #### Steps to reproduce the behavior: 1. install mitmproxy 5.1.1 on Fedora rawhide 2. mitmproxy 3. pytest -v There are: ``` =================== 303 failed, 994 passed, 2 xfailed, 115 warnings, 182 errors in 72.86s (0:01:12) ==================== ``` Most of them throw a `TypeError: Subscripted generics cannot be used with class and instance checks` and have a stack trace similar to: ``` ___________________________________ ERROR at setup of TestHTTPS.test_clientcert_dir ____________________________________ cls = <class 'test.mitmproxy.proxy.test_server.TestHTTPS'> @classmethod def setup_class(cls): cls.server = pathod.test.Daemon( ssl=cls.ssl, ssloptions=cls.ssloptions) cls.server2 = pathod.test.Daemon( ssl=cls.ssl, ssloptions=cls.ssloptions) > cls.options = cls.get_options() test/mitmproxy/tservers.py:146: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ test/mitmproxy/tservers.py:179: in get_options return options.Options( mitmproxy/options.py:50: in __init__ self.add_option( mitmproxy/optmanager.py:109: in add_option self._options[name] = _Option(name, typespec, default, help, choices) mitmproxy/optmanager.py:34: in __init__ typecheck.check_option_type(name, default, typespec) mitmproxy/utils/typecheck.py:73: in check_option_type elif not isinstance(value, typeinfo): /usr/lib64/python3.9/typing.py:649: in __instancecheck__ return self.__subclasscheck__(type(obj)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = typing.Optional[str], cls = <class 'NoneType'> def __subclasscheck__(self, cls): > raise TypeError("Subscripted generics cannot be used with" " class and instance checks") E TypeError: Subscripted generics cannot be used with class and instance checks /usr/lib64/python3.9/typing.py:652: TypeError ``` #### System Information ``` Traceback (most recent call last): File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/bin/./mitmproxy", line 11, in <module> load_entry_point('mitmproxy==5.1.1', 'console_scripts', 'mitmproxy')() File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/tools/_main.py", line 147, in mitmproxy run(console.master.ConsoleMaster, cmdline.mitmproxy, args) File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/tools/_main.py", line 71, in run opts = options.Options() File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/options.py", line 50, in __init__ self.add_option( File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/optmanager.py", line 109, in add_option self._options[name] = _Option(name, typespec, default, help, choices) File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/optmanager.py", line 34, in __init__ typecheck.check_option_type(name, default, typespec) File "/builddir/build/BUILDROOT/mitmproxy-5.1.1-1.fc33.x86_64/usr/lib/python3.9/site-packages/mitmproxy/utils/typecheck.py", line 73, in check_option_type elif not isinstance(value, typeinfo): File "/usr/lib64/python3.9/typing.py", line 649, in __instancecheck__ return self.__subclasscheck__(type(obj)) File "/usr/lib64/python3.9/typing.py", line 652, in __subclasscheck__ raise TypeError("Subscripted generics cannot be used with" TypeError: Subscripted generics cannot be used with class and instance checks ```
Ah, wonderful. Thanks for the early heads-up! 😃 Looks like we need to adjust our type-checking for 3.9. I presume we want to wait with this until GitHub Actions allows us to run CI for _some_ Python 3.9 release. Small Update: #4174 introduces CI coverage for Python 3.9, now it's a matter of fixing the actual issue. :)
2020-08-27T12:53:13
mitmproxy/mitmproxy
4,181
mitmproxy__mitmproxy-4181
[ "4167" ]
901a8dd7d44c99d5d459b5c3f486e77fdf1f9d95
diff --git a/mitmproxy/addons/export.py b/mitmproxy/addons/export.py --- a/mitmproxy/addons/export.py +++ b/mitmproxy/addons/export.py @@ -18,7 +18,11 @@ def cleanup_request(f: flow.Flow) -> http.HTTPRequest: assert isinstance(f, http.HTTPFlow) request = f.request.copy() request.decode(strict=False) - # a bit of clean-up - these headers should be automatically set by curl/httpie + return request + + +def pop_headers(request: http.HTTPRequest) -> http.HTTPRequest: + # Remove some headers that are redundant for curl/httpie export request.headers.pop('content-length') if request.headers.get("host", "") == request.host: request.headers.pop("host") @@ -53,6 +57,7 @@ def request_content_for_console(request: http.HTTPRequest) -> str: def curl_command(f: flow.Flow) -> str: request = cleanup_request(f) + request = pop_headers(request) args = ["curl"] for k, v in request.headers.items(multi=True): if k.lower() == "accept-encoding": @@ -70,6 +75,7 @@ def curl_command(f: flow.Flow) -> str: def httpie_command(f: flow.Flow) -> str: request = cleanup_request(f) + request = pop_headers(request) args = ["http", request.method, request.url] for k, v in request.headers.items(multi=True): args.append(f"{k}: {v}")
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 @@ -144,6 +144,7 @@ def test_req_and_resp_present(self, get_flow): def test_get_request_present(self, get_request): assert b"header: qvalue" in export.raw(get_request) + assert b"content-length: 0" in export.raw_request(get_request) def test_get_response_present(self, get_response): delattr(get_response, 'request') @@ -163,6 +164,7 @@ def test_tcp(self, tcp_flow): class TestRawRequest: def test_get(self, get_request): assert b"header: qvalue" in export.raw_request(get_request) + assert b"content-length: 0" in export.raw_request(get_request) def test_no_request(self, get_response): delattr(get_response, 'request')
Host header shown in UI but missing in request #### Problem Description The Host header shows in the request flow UI but isn't in the raw request export #### Steps to reproduce the behavior: 1. Capture a request to https://github.com for example 2. Host header appears in the flow view of request 3. Export as `raw_request` or `raw` 4. Host header is missing in the output file #### System Information Mitmproxy: 6.0.0.dev (+49, commit c48a2fc) Python: 3.8.5 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-5.7.15-1-MANJARO-x86_64-with-glibc2.2.5
I think in addons/export.py, function raw_request should not return cleanup_request(f) , it should just return f.request. I think you're right, it looks like the relevant lines in `cleanup_request` are only meant for httpie and curl exports. https://github.com/mitmproxy/mitmproxy/blob/c48a2fcc4fa057d45b630bc779ec7c392e94b3fa/mitmproxy/addons/export.py#L15-L24 Thanks @zlowly! If one of you could send a PR, that'd be fantastic. ✨
2020-08-27T22:40:40
mitmproxy/mitmproxy
4,185
mitmproxy__mitmproxy-4185
[ "4152" ]
2aacf94a63c7e0c396d6254356ba9739c7319077
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 @@ -11,6 +11,7 @@ import tempfile import typing # noqa import contextlib +import threading import urwid @@ -171,7 +172,9 @@ def spawn_external_viewer(self, data, contenttype): signals.status_message.send( message="Can't start external viewer: %s" % " ".join(c) ) - os.unlink(name) + # add a small delay before deletion so that the file is not removed before being loaded by the viewer + t = threading.Timer(1.0, os.unlink, args=[name]) + t.start() def set_palette(self, opts, updated): self.ui.register_palette(
View response in Firefox gives file not found #### Problem Description Hitting `v` on a flow opens up firefox pointing to a temp mitmproxy file but the file doesn't exist #### Steps to reproduce the behavior: 1. Capture a request 2. Press v in the flow view of request and 2 for viewing response 3. Firefox opens up to view the response html page but only displays file not found e.g. `Firefox can’t find the file at /tmp/mproxynqb8uytn.html`. (Hitting `e` and editing the response works correctly and opens up the response as a tmp file in my editor) #### System Information Mitmproxy: 5.1.1 Python: 3.8.3 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-5.6.19-2-MANJARO-x86_64-with-glibc2.2.5
Thanks! The problem is likely in https://github.com/mitmproxy/mitmproxy/blob/408bd7fd4c5ed147ce2951428bfdd6206e1eb8b8/mitmproxy/tools/console/master.py#L139-L174. I'd guess that the process we're calling exits before your Firefox renders and we've then already unlinked. Not sure what the best approach is, but I guess moving the unlink to a thread with a timeout should fix this main issue.
2020-08-28T16:15:19
mitmproxy/mitmproxy
4,210
mitmproxy__mitmproxy-4210
[ "3015" ]
f135be8e65de7564d628a1535bd198139a153572
diff --git a/mitmproxy/addons/core.py b/mitmproxy/addons/core.py --- a/mitmproxy/addons/core.py +++ b/mitmproxy/addons/core.py @@ -56,6 +56,8 @@ def set(self, option: str, value: str = "") -> None: strings and integers are set to None (if permitted), and sequences are emptied. Boolean values can be true, false or toggle. Multiple values are concatenated with a single space. + Sequences are set using multiple invocations to set for + the same option. """ strspec = f"{option}={value}" try: diff --git a/mitmproxy/optmanager.py b/mitmproxy/optmanager.py --- a/mitmproxy/optmanager.py +++ b/mitmproxy/optmanager.py @@ -1,3 +1,4 @@ +import collections import contextlib import blinker import blinker._saferef @@ -91,7 +92,7 @@ class OptManager: mutation doesn't change the option state inadvertently. """ def __init__(self): - self.deferred: typing.Dict[str, str] = {} + self.deferred: typing.Dict[str, typing.List[str]] = {} self.changed = blinker.Signal() self.errored = blinker.Signal() # Options must be the last attribute here - after that, we raise an @@ -295,7 +296,7 @@ def set(self, *spec, defer=False): are added. """ vals = {} - unknown = {} + unknown: typing.Dict[str, typing.List[str]] = collections.defaultdict(list) for i in spec: parts = i.split("=", maxsplit=1) if len(parts) == 1: @@ -303,9 +304,9 @@ def set(self, *spec, defer=False): else: optname, optval = parts[0], parts[1] if optname in self._options: - vals[optname] = self.parse_setval(self._options[optname], optval) + vals[optname] = self.parse_setval(self._options[optname], optval, vals.get(optname)) else: - unknown[optname] = optval + unknown[optname].append(optval) if defer: self.deferred.update(unknown) elif unknown: @@ -318,15 +319,16 @@ def process_deferred(self): have since been added. """ update = {} - for optname, optval in self.deferred.items(): + for optname, optvals in self.deferred.items(): if optname in self._options: - optval = self.parse_setval(self._options[optname], optval) - update[optname] = optval + for optval in optvals: + optval = self.parse_setval(self._options[optname], optval, update.get(optname)) + update[optname] = optval self.update(**update) for k in update.keys(): del self.deferred[k] - def parse_setval(self, o: _Option, optstr: typing.Optional[str]) -> typing.Any: + def parse_setval(self, o: _Option, optstr: typing.Optional[str], currentvalue: typing.Any) -> typing.Any: """ Convert a string to a value appropriate for the option type. """ @@ -357,7 +359,10 @@ def parse_setval(self, o: _Option, optstr: typing.Optional[str]) -> typing.Any: if not optstr: return [] else: - return getattr(self, o.name) + [optstr] + if currentvalue: + return getattr(self, o.name) + currentvalue + [optstr] + else: + return getattr(self, o.name) + [optstr] raise NotImplementedError("Unsupported option type: %s", o.typespec) def make_parser(self, parser, optname, metavar=None, short=None): diff --git a/mitmproxy/tools/cmdline.py b/mitmproxy/tools/cmdline.py --- a/mitmproxy/tools/cmdline.py +++ b/mitmproxy/tools/cmdline.py @@ -27,6 +27,8 @@ def common_options(parser, opts): Set an option. When the value is omitted, booleans are set to true, strings and integers are set to None (if permitted), and sequences are emptied. Boolean values can be true, false or toggle. + Sequences are set using multiple invocations to set for + the same option. """ ) parser.add_argument(
diff --git a/test/mitmproxy/test_optmanager.py b/test/mitmproxy/test_optmanager.py --- a/test/mitmproxy/test_optmanager.py +++ b/test/mitmproxy/test_optmanager.py @@ -71,7 +71,7 @@ def test_defaults(): def test_required_int(): o = TO() with pytest.raises(exceptions.OptionsError): - o.parse_setval(o._options["required_int"], None) + o.parse_setval(o._options["required_int"], None, None) def test_deepcopy(): @@ -439,6 +439,9 @@ def test_set(): opts.set("seqstr") assert opts.seqstr == [] + opts.set(*('seqstr=foo', 'seqstr=bar')) + assert opts.seqstr == ["foo", "bar"] + with pytest.raises(exceptions.OptionsError): opts.set("deferredoption=wobble") @@ -450,3 +453,12 @@ def test_set(): opts.process_deferred() assert "deferredoption" not in opts.deferred assert opts.deferredoption == "wobble" + + opts.set(*('deferredsequenceoption=a', 'deferredsequenceoption=b'), defer=True) + assert "deferredsequenceoption" in opts.deferred + opts.process_deferred() + assert "deferredsequenceoption" in opts.deferred + opts.add_option("deferredsequenceoption", typing.Sequence[str], [], "help") + opts.process_deferred() + assert "deferredsequenceoption" not in opts.deferred + assert opts.deferredsequenceoption == ["a", "b"]
No way to set a sequence option on the command line ##### Steps to reproduce the problem: 1. Create a file `/tmp/example.py` with the following text: ```python import typing from mitmproxy import ctx class Example: def load(self, loader): loader.add_option(name='myoption', typespec=typing.Sequence[str], default=[], help='') def response(self, flow): ctx.log.info(repr(ctx.options.myoption)) addons = [Example()] ``` 2. Run `mitmdump -s /tmp/example.py --set myoption=foo --set myoption=bar` 3. Run a request through it: `curl -sx http://localhost:8080 http://httpbin.org/get` 4. Observe that `['bar']` is printed, meaning that `myoption` is set to a sequence of one element — the last one passed on the command line, with the first one ignored. ##### Any other comments? What have you tried so far? Looking at [the code](https://github.com/mitmproxy/mitmproxy/blob/79fc4e8ad6cab5181ba39d7f0b0d40f7c11a8389/mitmproxy/optmanager.py#L312-L316), I’m not immediately sure why the multiple `--set` don’t work as I expected them to. ##### System information Mitmproxy: 4.0.0 (79fc4e8) Python: 3.5.2 OpenSSL: OpenSSL 1.1.0h 27 Mar 2018 Platform: Linux-4.4.0-116-generic-x86_64-with-Ubuntu-16.04-xenial
Thanks for the concise example, this looks like a bug! I will take a look at this :) To solve this properly, we will have to define a format for sequences of strings, and teach the `parse_setval` function to know about it. @madt1m mad a valiant attempt to avoid doing this, but I don't think it works. ;) @cortesi could something in line with the good ol' $PATH-like format do the trick? --set myopt="opt1;opt2;..." I am using semicolon, because i guess that colon could be part of a string. Or, maybe, give the user the possibility to define its own delimiter? That's tricky because it's plausible to have any of those delimiters in e.g. a regex pattern. I'm afraid we have to go the strenuous route and add an additional "temp dict" argument to `parse_setval`. I don't want there to be any ambiguity about set on the command-line or in the command prompt: if you set an option, you over-write what was there before in toto. So no book-keeping between --set options, please. I suggest we do two things: - Teach `--set` to know about delimited strings. I think `;` or `,` are both fine, and add backslash escaping. This gets complicated in the presence of a shell, but users are familiar with this from all sorts of contexts, and it's bearable. - I'd be happy to have an `--append` command-line option and matching command that appends a value to a sequence option. This can be used where we don't mind if update is called after every append. We also might need a better name than "append" which is a bit over-loaded. I'll manage to allocate some time in this weekend for this. I'll try to come up with a feasible solution :) Just to chime in: This bug / limitation has bit me, as well. I'm going to have to use a string option instead with a custom delimiter and hand-parse it myself to upgrade from MITMProxy 2 (where I just used argparse) to 4. I'm having the same issue, but with `server_replay_use_headers`. There doesn't seem to be a command-line argument to add such headers and using `--set server_replay_use_headers=headera,headerb` or `--set server_replay_use_headers=headera --set server_replay_use_headers=headerb` doesn't work correctly. Is there any way to circumvent this limitation? I tried adding an inline script to do something, but it doesn't seem to work. I.e. ``` from mitmproxy import ctx ctx.options.server_replay_ignore_params = [ "one", "two" ] ``` It looks correct in `mitmproxy`, but it does not seem to actually do anything. <img width="371" alt="image" src="https://user-images.githubusercontent.com/641248/93106496-a0c28100-f6b0-11ea-8806-1fe60f91cd30.png">
2020-09-26T11:40:47
mitmproxy/mitmproxy
4,239
mitmproxy__mitmproxy-4239
[ "4231" ]
9a790d7afec4413c4ab358706e5c53aad3310f06
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 @@ -357,6 +357,7 @@ def _process_flow(self, f): def get_response(): self.send_request_headers(f.request) + if f.request.stream: chunks = self.read_request_body(f.request) if callable(f.request.stream): 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 @@ -1,6 +1,7 @@ import threading import time import functools +import types from typing import Dict, Callable, Any, List, Optional # noqa import h2.exceptions @@ -602,6 +603,7 @@ def send_request_headers(self, request): self.raise_zombie, self.server_stream_id, headers, + end_stream=(False if request.content or request.trailers or request.stream else True), priority_exclusive=priority_exclusive, priority_depends_on=priority_depends_on, priority_weight=priority_weight, @@ -618,12 +620,13 @@ def send_request_body(self, request, chunks): # nothing to do here return - self.connections[self.server_conn].safe_send_body( - self.raise_zombie, - self.server_stream_id, - chunks, - end_stream=(request.trailers is None), - ) + if isinstance(chunks, types.GeneratorType) or (chunks and chunks[0]): + self.connections[self.server_conn].safe_send_body( + self.raise_zombie, + self.server_stream_id, + chunks, + end_stream=(request.trailers is None), + ) @detect_zombie_stream def send_request_trailers(self, request):
diff --git a/test/mitmproxy/proxy/protocol/test_http2.py b/test/mitmproxy/proxy/protocol/test_http2.py --- a/test/mitmproxy/proxy/protocol/test_http2.py +++ b/test/mitmproxy/proxy/protocol/test_http2.py @@ -192,7 +192,7 @@ def teardown_class(cls): _Http2ServerBase.teardown_class() -class TestSimple(_Http2Test): +class TestSimpleRequestWithBody(_Http2Test): request_body_buffer = b'' @classmethod @@ -226,7 +226,7 @@ def handle_server_event(cls, event, h2_conn, rfile, wfile): cls.request_body_buffer += event.data return True - def test_simple(self): + def test_simple_request_with_body(self): response_body_buffer = b'' h2_conn = self.setup_connection() @@ -274,6 +274,77 @@ def test_simple(self): assert response_body_buffer == b'response body' +class TestSimpleRequestWithoutBody(_Http2Test): + @classmethod + def handle_server_event(cls, event, h2_conn, rfile, wfile): + if isinstance(event, h2.events.ConnectionTerminated): + return False + elif isinstance(event, h2.events.RequestReceived): + assert (b'self.client-foo', b'self.client-bar-1') in event.headers + elif isinstance(event, h2.events.StreamEnded): + import warnings + with warnings.catch_warnings(): + # Ignore UnicodeWarning: + # h2/utilities.py:64: UnicodeWarning: Unicode equal comparison + # failed to convert both arguments to Unicode - interpreting + # them as being unequal. + # elif header[0] in (b'cookie', u'cookie') and len(header[1]) < 20: + + warnings.simplefilter("ignore") + h2_conn.send_headers(event.stream_id, [ + (':status', '200'), + ]) + h2_conn.send_data(event.stream_id, b'response body') + h2_conn.end_stream(event.stream_id) + wfile.write(h2_conn.data_to_send()) + wfile.flush() + elif isinstance(event, h2.events.DataReceived): + return False + return True + + def test_simple(self): + response_body_buffer = b'' + h2_conn = self.setup_connection() + + self._send_request( + self.client.wfile, + h2_conn, + headers=[ + (':authority', "127.0.0.1:{}".format(self.server.server.address[1])), + (':method', 'GET'), + (':scheme', 'https'), + (':path', '/'), + ('self.client-FoO', 'self.client-bar-1'), + ]) + + done = False + while not done: + try: + raw = b''.join(http2.read_raw_frame(self.client.rfile)) + events = h2_conn.receive_data(raw) + except exceptions.HttpException: + print(traceback.format_exc()) + assert False + + self.client.wfile.write(h2_conn.data_to_send()) + self.client.wfile.flush() + + for event in events: + if isinstance(event, h2.events.DataReceived): + response_body_buffer += event.data + elif isinstance(event, h2.events.StreamEnded): + done = True + + h2_conn.close_connection() + self.client.wfile.write(h2_conn.data_to_send()) + self.client.wfile.flush() + + assert len(self.master.state.flows) == 1 + assert self.master.state.flows[0].response.status_code == 200 + assert self.master.state.flows[0].response.content == b'response body' + assert response_body_buffer == b'response body' + + class TestRequestWithPriority(_Http2Test): @classmethod @@ -920,6 +991,7 @@ def handle_server_event(cls, event, h2_conn, rfile, wfile): elif isinstance(event, h2.events.DataReceived): data = event.data assert data + print(event) h2_conn.close_connection(error_code=5, last_stream_id=42, additional_data=data) wfile.write(h2_conn.data_to_send()) wfile.flush() @@ -961,6 +1033,7 @@ def requestheaders(self, f): connection_terminated_event = event done = True except: + print(traceback.format_exc()) break if streaming:
get HTTP ERROR 413 return mitmproxy version: master newest python version: 3.8.5 OS: windows 10 browser: Chrome 85 use mitmproxy browser `https://ww1.sinaimg.cn/mw600/5f789f8fgy1gjnnwi718sj20s50funk3.jpg` ,get return 413. i find, commit `828ba0c2e79d8c54806a1c9eefb6007abc8aabc0` is normal, commit `c0f62cc559ae4f0778d6079a2b31d2ce0309dda6` is return ERROR 413.
We just had this in #4221 and it looked like it's fixed in master (@Kriechi). But I can confirm that HEAD is broken. Interestingly it does work for the URL in #4221. So it looks like some of the HTTP/2 code changed and made it compatible with one server (https://g.alicdn.com/kg/kmd-adapter/0.0.6/index.js) while breaking compatibility with the other (https://ww1.sinaimg.cn/mw600/5f789f8fgy1gjnnwi718sj20s50funk3.jpg). I can confirm that 828ba0c2e79d8c54806a1c9eefb6007abc8aabc0 works for _both_ URLs. Then c0f62cc559ae4f0778d6079a2b31d2ce0309dda6 broke both. And then HEAD (currently 0f963248872b3ae7c6d9b5065cd9ea79ae73f153) only works for one of them. > We just had this in #4221 and it looked like it's fixed in master (@Kriechi). But I can confirm that HEAD is broken. Interestingly it does work for the URL in #4221. > > So it looks like some of the HTTP/2 code changed and made it compatible with one server (https://g.alicdn.com/kg/kmd-adapter/0.0.6/index.js) while breaking compatibility with the other (https://ww1.sinaimg.cn/mw600/5f789f8fgy1gjnnwi718sj20s50funk3.jpg). > > I can confirm that [828ba0c](https://github.com/mitmproxy/mitmproxy/commit/828ba0c2e79d8c54806a1c9eefb6007abc8aabc0) works for _both_ URLs. > > Then [c0f62cc](https://github.com/mitmproxy/mitmproxy/commit/c0f62cc559ae4f0778d6079a2b31d2ce0309dda6) broke both. > > And then HEAD (currently [0f96324](https://github.com/mitmproxy/mitmproxy/commit/0f963248872b3ae7c6d9b5065cd9ea79ae73f153)) only works for one of them. I have tested this many times and found that the 413 error does not occur 100% of the time. It's possible that it will be normal after a while, but these cases have one thing in common, all the servers that return exceptions are using Tengine (https://tengine.taobao.org/), which is a Nginx-based HTTP server. www.taobao.com,www.bilibili.com uses Tengine, and you can see a lot of 413 code errors when you visit both sites. Hopefully, this finding will help. (I've also found a lot of 501 code errors that appear and disappear for no apparent reason, not sure if it's due to a change in the h2 module version.) @Prinzhorn thanks for bisecting! 🎉 I can't spot an obvious bug - but based on past experience I'm inclined to blame a faulty or non-RFC-compliant implementation in tengine or an outdated library on the server... We've seen lots of incompatibilities in the early days of HTTP/2. Some vendors even claimed "due to performance benefit we chose to break RFC compliance"... I'll try to find some time and do another deep-dive, but unless anyone reports a similar problem with other webserver (most importantly the "real" nginx), I think we need to find a workaround for tengine specifically... > @Prinzhorn thanks for bisecting! tada @Kriechi that was mostly @bigfoxtail's work > I can't spot an obvious bug - but based on past experience I'm inclined to blame a faulty or non-RFC-compliant implementation in tengine or an outdated library on the server... We've seen lots of incompatibilities in the early days of HTTP/2. Some vendors even claimed "due to performance benefit we chose to break RFC compliance"... > > I'll try to find some time and do another deep-dive, but unless anyone reports a similar problem with other webserver (most importantly the "real" nginx), I think we need to find a workaround for tengine specifically... Even if the server is not RFC compliant, the URLs work in Firefox, Chromium, curl (with `--http2`) and Burp Suite (with HTTP/2 enabled). Obviously they have a lot more resources to make their stack compatible to almost anything. I just wanted to point that out. But like you said, if this doesn't become a more widespread issue we might just wait and see what happens. On the other hand it _did_ work at some point. I found another module httpx that uses http2 that works fine. In the httpcore module used by httpx I found this part of the code. https://github.com/encode/httpcore/blob/master/httpcore/_sync/http2.py Line 286: ``` # Send the request. seen_headers = set(key for key, value in headers) has_body = ( b"content-length" in seen_headers or b"transfer-encoding" in seen_headers ) self.send_headers(method, url, headers, has_body, timeout) if has_body: self.send_body(stream, timeout) ``` In c0f62cc559ae4f0778d6079a2b31d2ce0309dda6 you have modified some codes ``` - end_stream=self.no_request_body, ``` and ``` - if not self.no_request_body: - self.connections[self.server_conn].safe_send_body( - self.raise_zombie, - self.server_stream_id, - chunks - ) ``` Data was sent without determining the existence of the request body. That seems to be the problem.
2020-10-17T14:58:52
mitmproxy/mitmproxy
4,246
mitmproxy__mitmproxy-4246
[ "4245" ]
c5bd7b1ae1eb7b6280b77cab14f173d18a211062
diff --git a/mitmproxy/addons/modifyheaders.py b/mitmproxy/addons/modifyheaders.py --- a/mitmproxy/addons/modifyheaders.py +++ b/mitmproxy/addons/modifyheaders.py @@ -83,14 +83,21 @@ def response(self, flow): self.run(flow, flow.response.headers) def run(self, flow: http.HTTPFlow, hdrs: Headers) -> None: - # unset all specified headers + matches = [] + + # first check all the filters against the original, unmodified flow for spec in self.replacements: - if spec.matches(flow): + matches.append(spec.matches(flow)) + + # unset all specified headers + for i, spec in enumerate(self.replacements): + if matches[i]: hdrs.pop(spec.subject, None) # set all specified headers if the replacement string is not empty - for spec in self.replacements: - if spec.matches(flow): + + for i, spec in enumerate(self.replacements): + if matches[i]: try: replacement = spec.read_replacement() except OSError as e:
diff --git a/test/mitmproxy/addons/test_modifyheaders.py b/test/mitmproxy/addons/test_modifyheaders.py --- a/test/mitmproxy/addons/test_modifyheaders.py +++ b/test/mitmproxy/addons/test_modifyheaders.py @@ -113,6 +113,19 @@ def test_modify_headers(self): mh.response(f) assert "one" not in f.response.headers + # test modifying a header that is also part of the filter expression + # https://github.com/mitmproxy/mitmproxy/issues/4245 + tctx.configure( + mh, + modify_headers=[ + "/~hq ^user-agent:.+Mozilla.+$/user-agent/Definitely not Mozilla ;)" + ] + ) + f = tflow.tflow() + f.request.headers["user-agent"] = "Hello, it's me, Mozilla" + mh.request(f) + assert "Definitely not Mozilla ;)" == f.request.headers["user-agent"] + @pytest.mark.parametrize("take", [True, False]) def test_taken(self, take): mh = ModifyHeaders()
v4 --replacements vs v5 --modify-headers I'm trying to replace the `User-Agent` request header if it contains a certain string. This works with "mitmproxy-4.0.4-linux": ``` ./mitmproxy --replacements ":~hq User-Agent:Mozilla(.+):CUSTOMAGENT" ``` With "mitmproxy-5.2-linux", this at least replaces the `User-Agent`, but is missing my "certain string condition": ``` ./mitmproxy --modify-headers "|~hq .+|User-Agent|CUSTOMAGENT" ``` How do I add my `Mozilla` condition in v5? None of these work: ``` ./mitmproxy --modify-headers "|~hq ^(.*?)Mozilla(.*?)$|User-Agent|CUSTOMAGENT" ./mitmproxy --modify-headers "/~hq .*?Mozilla.*?/User-Agent/CUSTOMAGENT" ./mitmproxy --modify-headers "|~hq Mozilla|User-Agent|CUSTOMAGENT" ./mitmproxy --modify-headers "|~hq User-Agent: Mozilla|User-Agent|CUSTOMAGENT" ./mitmproxy --modify-headers "|~hq \"^(.*?)Mozilla(.*?)$\"|User-Agent|CUSTOMAGENT" ``` I've been trying for hours, and I feel like I've tried every variation under the sun. There's a very small chance it's a bug, but most likely I'm just doing it wrong. If it matters, this system is Ubuntu 16.04.
I've been digging into this and this is definitely a bug in the implementation. Will follow up with details. https://github.com/mitmproxy/mitmproxy/blob/a203b69ba97eab47302edbb9b378eff353550132/mitmproxy/addons/modifyheaders.py#L83-L99 Given your example line 85 to 87 remove the `user-agent` header. Then line 91 tries to match the flow against the filter. But the header is gone, so it cannot match. I'm not sure why it's implemented this way, but I think both loops (which on the first two level share the exact same code) should be combined into one. Essentially moving the `pop` from the first loop into the else block here https://github.com/mitmproxy/mitmproxy/blob/a203b69ba97eab47302edbb9b378eff353550132/mitmproxy/addons/modifyheaders.py#L98-L99 I'm working on a fix.
2020-10-24T08:54:20
mitmproxy/mitmproxy
4,278
mitmproxy__mitmproxy-4278
[ "2894" ]
0fa7c463683149a0b400108420efc09ff72f11a5
diff --git a/mitmproxy/tools/console/common.py b/mitmproxy/tools/console/common.py --- a/mitmproxy/tools/console/common.py +++ b/mitmproxy/tools/console/common.py @@ -191,7 +191,7 @@ def render(self, size, focus=False): text = text[::-1] attr = attr[::-1] - text_len = len(text) # TODO: unicode? + text_len = urwid.util.calc_width(text, 0, len(text)) if size is not None and len(size) > 0: width = size[0] else: @@ -206,8 +206,10 @@ def render(self, size, focus=False): c_text = text c_attr = attr else: - visible_len = width - len(SYMBOL_ELLIPSIS) - visible_text = text[0:visible_len] + trim = urwid.util.calc_trim_text(text, 0, width - 1, 0, width - 1) + visible_text = text[0:trim[1]] + if trim[3] == 1: + visible_text += ' ' c_text = visible_text + SYMBOL_ELLIPSIS c_attr = (urwid.util.rle_subseg(attr, 0, len(visible_text.encode())) + [('focus', len(SYMBOL_ELLIPSIS.encode()))])
diff --git a/test/mitmproxy/tools/console/test_common.py b/test/mitmproxy/tools/console/test_common.py --- a/test/mitmproxy/tools/console/test_common.py +++ b/test/mitmproxy/tools/console/test_common.py @@ -36,3 +36,10 @@ def test_format_keyvals(): ("aa", wrapped) ] ) + + +def test_truncated_text(): + half_width_text = common.TruncatedText("Half-width", []) + full_width_text = common.TruncatedText("FULL-WIDTH", []) + assert half_width_text.render((10,)) + assert full_width_text.render((10,))
Properly check for UTF8 console ##### Steps to reproduce the problem: 1. `mitmproxy` and `mitmproxy --save-stream-file +/tmp/mitmdump` 2. select some event, enter 3. scroll down ```python Traceback (most recent call last): File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/mitmproxy/tools/console/master.py", line 216, in run self.loop.run() File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 286, in run self._run() File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 384, in _run self.event_loop.run() File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 788, in run self._loop() File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 816, in _loop self._entering_idle() File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 777, in _entering_idle callback() File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 572, in entering_idle self.draw_screen() File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/main_loop.py", line 586, in draw_screen canvas = self._topmost_widget.render(self.screen_size, focus=True) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/decoration.py", line 226, in render canv = self._original_widget.render(size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 1765, in render canv = get_delegate(self).render(size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/listbox.py", line 489, in render focus_canvas = focus_widget.render((maxcol,), focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/widget.py", line 1004, in render return apply_text_layout(text, attr, trans, maxcol) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/canvas.py", line 1315, in apply_text_layout return TextCanvas(t, a, c, maxcol=maxcol) File "/usr/local/Cellar/mitmproxy/3.0.0/libexec/lib/python3.6/site-packages/urwid/canvas.py", line 358, in __init__ raise CanvasError("Canvas text is wider than the maxcol specified \n%r\n%r\n%r"%(maxcol,widths,text)) urwid.canvas.CanvasError: Canvas text is wider than the maxcol specified 153 [153, 153, 154, 125] [b'[REDACTED NAME]: ....$.......?.E=?[LONG REDACTED GLIBBERISH]"] ``` ![pasted_image_22_02_18_18_36](https://user-images.githubusercontent.com/2737108/36554418-801662a6-17ff-11e8-88af-6c82a95c3d37.png) ##### System information <!-- Paste the output of "mitmproxy --version" here. --> ```shell $ mitmproxy --version Mitmproxy: 3.0.0 Python: 3.6.4 OpenSSL: OpenSSL 1.0.2n 7 Dec 2017 Platform: Darwin-13.4.0-x86_64-i386-64bit ``` (via Brew, installed earlier today, so should be the latest version) From the second run with dumping to file, this seems to be the binary form-data where it crashed. The request is to an API's upload function. ``` 2018-02-23 08:00:00 --Boundary+1DAA87079F6BACB5 Content-Disposition: form-data; name="[REDACTED NAME]"; filename="file" Content-Type: application/octet-stream ^A^@^@^@[REDACTED GLIBBERISH] ``` As I am not certain about the contents of the recorded data, so I won't post the dump public. However, I have keep it for now. Also might be another occurrence of #1796.
Basically it seems to render the raw binary data in too long lines. On a previous crash I got those values: ```python maxcol = 153 widths = [152, 153, 134, 153, 132, 154, 138, 98, 133, 154, 154, 153, 156, 153, 81, 121, 43, 154, 153, 154, 153, 153, 121, 153, 154, 153, 153, 153, 136, 102, 81, 149, 154, 154, 153, 131, 55, 153, 153, 153, 153, 154, 154, 155, 153, 114, 153, 11, 153, 83, 154, 72, 100, 109, 153, 156, 152, 143, 110, 110, 146, 117, 153, 64, 153, 145, 82, 131, 154, 153, 155, 153, 154, 155, 153, 133, 148, 83, 155, 153, 97, 154, 153, 153, 144, 102, 134, 117, 153, 133, 153, 133, 101, 154, 153, 130, 132, 154, 143, 108, 92, 91, 154, 153, 94, 153, 153, 105, 153, 87, 154, 105, 137, 88, 79, 124, 94, 138, 153, 154, 89, 132, 21, 154, 153, 153, 104, 133, 153, 154, 94, 100, 77, 153, 76, 137, 153, 153, 154, 153, 154, 154, 154, 153, 153, 118, 96, 148, 151, 154, 153, 110, 154, 35, 153, 154, 153, 153, 112, 151, 1, 153, 58, 125, 153, 153, 153, 154, 154, 153, 153, 41, 133, 86, 140, 153, 153, 154, 109, 125, 123, 153, 143, 62, 153, 154, 153, 17, 153, 85, 95, 133, 73, 122, 113, 102, 134, 156, 154, 153, 153, 155, 153, 93, 96, 131, 154, 154, 153, 153, 122, 132, 117, 144, 155, 154, 153, 32, 135, 156, 22, 153, 153, 122, 154, 125, 148, 6, 154, 153, 130, 140, 153, 155, 121, 108, 153, 154, 154, 55, 155, 154, 70, 154, 153, 153, 153, 153, 155, 34, 153, 153, 153, 155, 154, 34, 154, 153, 155, 155, 154, 152, 155, 153, 153, 13, 141, 28, 153, 117, 154, 153, 154, 119, 68, 153, 119, 86, 91, 153, 154, 153, 153, 154, 153, 28, 139, 154, 154, 27, 128, 153, 153, 153, 153, 154, 81, 103, 132, 134, 153, 84, 117, 66, 122, 154, 102, 152, 154, 140] ``` And the `text` was `[b'file: PK............?w4/\\ ` and _pages_ of glibberish and `']` Yeah, some lines are 1 or 2 characters to long: ```python print("[" + (", ".join(["+"+str(w-maxcol) if w > maxcol else "ok" for w in widths])) + "]") [ ok, ok, ok, ok, ok, +1, ok, ok, ok, +1, +1, ok, +3, ok, ok, ok, ok, +1, ok, +1, ok, ok, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, +1, +1, ok, ok, ok, ok, ok, ok, ok, +1, +1, +2, ok, ok, ok, ok, ok, ok, +1, ok, ok, ok, ok, +3, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, +1, ok, +2, ok, +1, +2, ok, ok, ok, ok, +2, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, +1, ok, ok, ok, +1, ok, ok, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, ok, +1, ok, ok, ok, +1, ok, ok, ok, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, ok, +1, ok, +1, +1, +1, ok, ok, ok, ok, ok, ok, +1, ok, ok, +1, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, +1, +1, ok, ok, ok, ok, ok, ok, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, ok, +3, +1, ok, ok, +2, ok, ok, ok, ok, +1, +1, ok, ok, ok, ok, ok, ok, +2, +1, ok, ok, ok, +3, ok, ok, ok, ok, +1, ok, ok, ok, +1, ok, ok, ok, ok, +2, ok, ok, ok, +1, +1, ok, +2, +1, ok, +1, ok, ok, ok, ok, +2, ok, ok, ok, ok, +2, +1, ok, +1, ok, +2, +2, +1, ok, +2, ok, ok, ok, ok, ok, ok, ok, +1, ok, +1, ok, ok, ok, ok, ok, ok, ok, +1, ok, ok, +1, ok, ok, ok, +1, +1, ok, ok, ok, ok, ok, ok, +1, ok, ok, ok, ok, ok, ok, ok, ok, ok, +1, ok, ok, +1, ok ] ``` Hi, I could not reproduce the issue on my system.But considering the recent fixes regarding the UI, i would advice you to update to the latest release candidate of mitmproxy. Same problem here when uploading an image to my server while mitmproxy is running bug still exist on recent version ```python Traceback (most recent call last): File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/mitmproxy/master.py", line 86, in run_loop loop() File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/main_loop.py", line 286, in run self._run() File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/main_loop.py", line 384, in _run self.event_loop.run() File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/main_loop.py", line 1484, in run reraise(*exc_info) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/compat.py", line 58, in reraise raise value File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/main_loop.py", line 1443, in faux_idle_callback callback() File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/main_loop.py", line 572, in entering_idle self.draw_screen() File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/main_loop.py", line 586, in draw_screen canvas = self._topmost_widget.render(self.screen_size, focus=True) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/decoration.py", line 226, in render canv = self._original_widget.render(size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/listbox.py", line 489, in render focus_canvas = focus_widget.render((maxcol,), focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 1765, in render canv = get_delegate(self).render(size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/container.py", line 1523, in render canv = w.render((maxcol,), focus=focus and item_focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/container.py", line 2087, in render focus = focus and self.focus_position == i) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/widget.py", line 144, in cached_render canv = fn(self, size, focus=focus) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/mitmproxy/tools/console/common.py", line 173, in render return urwid.TextCanvas([c_text.encode()], [c_attr], maxcol=width) File "/home/q/envs/mitmproxy_image/lib/python3.7/site-packages/urwid/canvas.py", line 358, in __init__ raise CanvasError("Canvas text is wider than the maxcol specified \n%r\n%r\n%r"%(maxcol,widths,text)) urwid.canvas.CanvasError: Canvas text is wider than the maxcol specified 23 [25] [b' \xe5\xb7\xa8\xe4\xb9\xb3.pic-b.com'] mitmproxy has crashed! ``` ```console $ mitmproxy --version Mitmproxy: 5.0.0 Python: 3.7.3 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-5.0.0-37-generic-x86_64-with-Ubuntu-19.04-disco ``` Yeah I am also having the same issue ``` ➜ mitmproxy --version Mitmproxy: 5.0.0 Python: 3.8.0 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Linux-4.19.88-1-MANJARO-x86_64-with-glibc2.2.5 ``` It would be of great help if anyone has steps to reliably and easily reproduce this. I have two terminal in one terminal I run `mitmproxy` and in another terminal I run the following commands: ``` ➜ export http_proxy=http://127.0.0.1:8080 ➜ curl google.com ``` after running `curl` command when I check the `mitmproxy` terminal window I have the same traceback as posted above. I had the same error. mitmproxy-5.0.1-linux I had to set "LANG=en_US.UTF-8" to be able to run mitmproxy, but the environment already had "LC_ALL=en_US.ISO-8859-1" (and LC_CTYPE). mitmproxy would work if # of putty window columns was <= 99, but crash if I expanded the window >= 100. ("tput cols"), but only after a new flow (curl google.com) with "application/*" as the type (maybe others, but not "text/html" since that seems not to be colored in the same way) When I unset "LC_ALL" & LC_CTYPE or set them to "en_US.UTF-8" it did not crash when window cols >= 100. Thanks @daspri! This sounds super promising, but I can't replicate it. Here's my setup: Console 1: ``` env LC_ALL=en_US.ISO-8859-1 LC_CTYPE=en_US.ISO-8859-1 LANG=en_US.UTF-8 mitmproxy ``` Console 2: ``` curl -x localhost:8080 -k https://google.com ``` Environment: ``` $ mitmproxy --version Mitmproxy: 6.0.0.dev (+19, commit 7b638f1) Python: 3.8.0 OpenSSL: OpenSSL 1.1.1 11 Sep 2018 Platform: Linux-4.4.0-18362-Microsoft-x86_64-with-glibc2.27 $ printenv EDITOR=nano GIT_HOME=/mnt/c/Users/user/git GOPATH=/home/user/git/go GPG_TTY=/dev/tty1 HOME=/home/user HOSTTYPE=x86_64 LANG=C.UTF-8 LOGNAME=user NAME=xps PATH=[clip] PWD=/mnt/c/Users/user SHELL=/usr/bin/fish SHLVL=1 SSH_AGENT_PID=520 SSH_AUTH_SOCK=/tmp/ssh-9r6AgD/agent.519 TERM=xterm-256color TOX_WORK_DIR=.tox-linux USER=user VIRTUAL_ENV=/home/user/venv WSLENV= WSL_DISTRO_NAME=Ubuntu _OLD_FISH_PROMPT_OVERRIDE=/home/user/venv ``` No matter how I resize the window, I don't get any exceptions. Any hints where the difference is? Try to run curl a few times. Sometimes the first run works and the 2nd or 3rd kills it. Screen 1: ``` > tput cols 120 > LANG=en_US.UTF8 LC_ALL=en_US.ISO-8859-1 ./mitmproxy --listen-host 127.0.0.1 ``` Screen 2: ``` > curl -k -x http://127.0.0.1:8080 "https://www.google.com" > curl -k -x http://127.0.0.1:8080 "https://www.google.com" > curl -k -x http://127.0.0.1:8080 "https://www.google.com" ``` Screen 1: ``` Traceback (most recent call last): File "mitmproxy/master.py", line 86, in run_loop File "site-packages/urwid/main_loop.py", line 286, in run File "site-packages/urwid/main_loop.py", line 384, in _run File "site-packages/urwid/main_loop.py", line 1484, in run File "site-packages/urwid/compat.py", line 58, in reraise File "asyncio/events.py", line 88, in _run File "site-packages/urwid/main_loop.py", line 1443, in faux_idle_callback File "site-packages/urwid/main_loop.py", line 572, in entering_idle File "site-packages/urwid/main_loop.py", line 586, in draw_screen File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/container.py", line 1086, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/decoration.py", line 226, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/container.py", line 1086, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/listbox.py", line 501, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/widget.py", line 1765, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/container.py", line 1523, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "site-packages/urwid/container.py", line 2087, in render File "site-packages/urwid/widget.py", line 144, in cached_render File "mitmproxy/tools/console/common.py", line 173, in render File "site-packages/urwid/canvas.py", line 358, in __init__ urwid.canvas.CanvasError: Canvas text is wider than the maxcol specified 15 [17] [b'\xe2\x80\xa6ntent missing]'] ``` It does not crash if "tput cols" is less than 100, or if I don't add "LC_ALL=en_US.ISO-8859-1". Doing exactly that works just fine for me. :( ![image](https://user-images.githubusercontent.com/1019198/71752350-094d3300-2e7f-11ea-8521-2441706cd023.png) Do you have that locale installed? "locale -a" ? ``` env -i LANG=C.UTF-8 LC_ALL=en_US ./mitmproxy --listen-host 127.0.0.1 ``` Will also crash for me, but lowercase US does not: ``` env -i LANG=C.UTF-8 LC_ALL=en_us ./mitmproxy --listen-host 127.0.0.1 ``` Crashes on first try with microsoft, second try with google. ``` curl -k -x http://127.0.0.1:8080 "https://www.microsoft.com" ``` Thanks for the instructions - I was able to replicate it. @mhils I can take a look at this Thank you so much! I can finally reproduce this by forcing mitmproxy to use UTF8 symbols here: https://github.com/mitmproxy/mitmproxy/blob/184384af57e81bce09469e2fefe6dbb134eda6ce/mitmproxy/tools/console/common.py#L98 and then running ``` env -i LANG=C.UTF-8 LC_ALL=C ~/venv/bin/mitmproxy ``` I have no idea how any of this works, but it looks like we need to adjust our UTF8 check: https://github.com/mitmproxy/mitmproxy/blob/184384af57e81bce09469e2fefe6dbb134eda6ce/mitmproxy/tools/_main.py#L21-L34 🤷‍♂ `mitmproxy --version` ``` bash Mitmproxy: 5.2 Python: 3.7.7+ OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Linux-4.19.150-1-MANJARO-x86_64-with-arch-Manjaro-Linux ``` `locale -a` ``` bash C en_US.utf8 ja_JP.utf8 POSIX zh_CN.utf8 ``` `tput cols` ``` bash 240 ``` ``` bash Traceback (most recent call last): File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/mitmproxy/master.py", line 86, in run_loop loop() File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/main_loop.py", line 287, in run self._run() File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/main_loop.py", line 385, in _run self.event_loop.run() File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/main_loop.py", line 1494, in run reraise(*exc_info) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/compat.py", line 58, in reraise raise value File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/main_loop.py", line 1454, in faux_idle_callback callback() File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/main_loop.py", line 574, in entering_idle self.draw_screen() File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/main_loop.py", line 588, in draw_screen canvas = self._topmost_widget.render(self.screen_size, focus=True) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 145, in cached_render canv = fn(self, size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 145, in cached_render canv = fn(self, size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/decoration.py", line 226, in render canv = self._original_widget.render(size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 145, in cached_render canv = fn(self, size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/container.py", line 1086, in render focus and self.focus_part == 'body') File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 145, in cached_render canv = fn(self, size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/listbox.py", line 445, in render focus_canvas = focus_widget.render((maxcol,), focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 145, in cached_render canv = fn(self, size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 1761, in render canv = get_delegate(self).render(size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 145, in cached_render canv = fn(self, size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/container.py", line 2125, in render focus = focus and self.focus_position == i) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/widget.py", line 145, in cached_render canv = fn(self, size, focus=focus) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/mitmproxy/tools/console/common.py", line 207, in render return urwid.TextCanvas([c_text.encode()], [c_attr], maxcol=width) File "/home/jimmy/.pyenv/versions/3.7-dev/lib/python3.7/site-packages/urwid/canvas.py", line 358, in __init__ raise CanvasError("Canvas text is wider than the maxcol specified \n%r\n%r\n%r"%(maxcol,widths,text)) urwid.canvas.CanvasError: Canvas text is wider than the maxcol specified 21 [26] [b'\xe2\x80\xa6": [Errno 101] \xe7\xbd\x91\xe7\xbb\x9c\xe4\xb8\x8d\xe5\x8f\xaf\xe8\xbe\xbe'] mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy ```
2020-11-05T17:41:26
mitmproxy/mitmproxy
4,292
mitmproxy__mitmproxy-4292
[ "4287" ]
4351262c9590b7a1783173cd8322a07a140dde6e
diff --git a/mitmproxy/addons/command_history.py b/mitmproxy/addons/command_history.py --- a/mitmproxy/addons/command_history.py +++ b/mitmproxy/addons/command_history.py @@ -39,7 +39,10 @@ def done(self): if ctx.options.command_history and len(self.history) >= self.VACUUM_SIZE: # vacuum history so that it doesn't grow indefinitely. history_str = "\n".join(self.history[-self.VACUUM_SIZE // 2:]) + "\n" - self.history_file.write_text(history_str) + try: + self.history_file.write_text(history_str) + except Exception as e: + ctx.log.alert(f"Failed writing to {self.history_file}: {e}") @command.command("commands.history.add") def add_command(self, command: str) -> None: @@ -48,9 +51,11 @@ def add_command(self, command: str) -> None: self.history.append(command) if ctx.options.command_history: - with self.history_file.open("a") as f: - f.write(f"{command}\n") - f.close() + try: + with self.history_file.open("a") as f: + f.write(f"{command}\n") + except Exception as e: + ctx.log.alert(f"Failed writing to {self.history_file}: {e}") self.set_filter('') @@ -62,7 +67,10 @@ def get_history(self) -> typing.Sequence[str]: @command.command("commands.history.clear") def clear_history(self): if self.history_file.exists(): - self.history_file.unlink() + try: + self.history_file.unlink() + except Exception as e: + ctx.log.alert(f"Failed deleting {self.history_file}: {e}") self.history = [] self.set_filter('')
diff --git a/test/mitmproxy/addons/test_command_history.py b/test/mitmproxy/addons/test_command_history.py --- a/test/mitmproxy/addons/test_command_history.py +++ b/test/mitmproxy/addons/test_command_history.py @@ -1,4 +1,8 @@ import os +from unittest.mock import patch +from pathlib import Path + +import pytest from mitmproxy.addons import command_history from mitmproxy.test import taddons @@ -22,16 +26,35 @@ def test_load_and_save(self, tmpdir): with open(history_file, "r") as f: assert f.read() == "cmd3\ncmd4\n" + @pytest.mark.asyncio + async def test_done_writing_failed(self): + ch = command_history.CommandHistory() + ch.VACUUM_SIZE = 1 + with taddons.context(ch) as tctx: + ch.history.append('cmd1') + ch.history.append('cmd2') + ch.history.append('cmd3') + tctx.options.confdir = '/non/existent/path/foobar1234/' + ch.done() + assert await tctx.master.await_log(f"Failed writing to {ch.history_file}") + def test_add_command(self): - history = command_history.CommandHistory() + ch = command_history.CommandHistory() - history.add_command('cmd1') - history.add_command('cmd2') + ch.add_command('cmd1') + ch.add_command('cmd2') + assert ch.history == ['cmd1', 'cmd2'] - assert history.history == ['cmd1', 'cmd2'] + ch.add_command('') + assert ch.history == ['cmd1', 'cmd2'] - history.add_command('') - assert history.history == ['cmd1', 'cmd2'] + @pytest.mark.asyncio + async def test_add_command_failed(self): + ch = command_history.CommandHistory() + with taddons.context(ch) as tctx: + tctx.options.confdir = '/non/existent/path/foobar1234/' + ch.add_command('cmd1') + assert await tctx.master.await_log(f"Failed writing to {ch.history_file}") def test_get_next_and_prev(self, tmpdir): ch = command_history.CommandHistory() @@ -133,6 +156,20 @@ def test_clear(self, tmpdir): ch.clear_history() + @pytest.mark.asyncio + async def test_clear_failed(self, monkeypatch): + ch = command_history.CommandHistory() + + with taddons.context(ch) as tctx: + tctx.options.confdir = '/non/existent/path/foobar1234/' + + with patch.object(Path, 'exists') as mock_exists: + mock_exists.return_value = True + with patch.object(Path, 'unlink') as mock_unlink: + mock_unlink.side_effect = IOError() + ch.clear_history() + assert await tctx.master.await_log(f"Failed deleting {ch.history_file}") + def test_filter(self, tmpdir): ch = command_history.CommandHistory()
crash accessing .mitmproxy/command_history #### Problem Description mitmproxy crashes if `.mitmproxy/command_history` is inaccessible due to permissions #### Steps to reproduce the behavior: ```$ mitmproxy --mode "reverse:https://qa1.onepeloton.com" -p 9999 Traceback (most recent call last): File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/master.py", line 86, in run_loop loop() File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/main_loop.py", line 287, in run self._run() File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/main_loop.py", line 385, in _run self.event_loop.run() File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/main_loop.py", line 1494, in run reraise(*exc_info) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/compat.py", line 58, in reraise raise value File "/usr/local/Cellar/[email protected]/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 80, in _run self._context.run(self._callback, *self._args) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/raw_display.py", line 416, in <lambda> wrapper = lambda: self.parse_input( File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/raw_display.py", line 515, in parse_input callback(processed, processed_codes) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/main_loop.py", line 412, in _update self.process_input(keys) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/main_loop.py", line 513, in process_input k = self._topmost_widget.keypress(self.screen_size, k) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/tools/console/window.py", line 310, in keypress k = super().keypress(size, k) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/urwid/container.py", line 1123, in keypress return self.footer.keypress((maxcol,),key) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/tools/console/statusbar.py", line 201, in keypress return self.ab.keypress(*args, **kwargs) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/tools/console/statusbar.py", line 149, in keypress self.prompt_execute(text) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/tools/console/statusbar.py", line 169, in prompt_execute msg = p(txt) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/tools/console/statusbar.py", line 113, in execute_command self.master.commands.call("commands.history.add", txt) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/command.py", line 243, in call return self.commands[command_name].func(*args) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/command.py", line 296, in wrapper return function(*args, **kwargs) File "/usr/local/Cellar/mitmproxy/5.3.0/libexec/lib/python3.9/site-packages/mitmproxy/addons/command_history.py", line 51, in add_command with self.history_file.open("a") as f: File "/usr/local/Cellar/[email protected]/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/pathlib.py", line 1241, in open return io.open(self, mode, buffering, encoding, errors, newline, File "/usr/local/Cellar/[email protected]/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/pathlib.py", line 1109, in _opener return self._accessor.open(self, flags, mode) PermissionError: [Errno 13] Permission denied: '/Users/***/.mitmproxy/command_history' mitmproxy has crashed! Please lodge a bug report at: https://github.com/mitmproxy/mitmproxy``` #### System Information Mitmproxy: 5.3.0 Python: 3.9.0 OpenSSL: OpenSSL 1.1.1h 22 Sep 2020 Platform: macOS-10.15.7-x86_64-i386-64bit
What would be the expected behavior? mitmproxy controls `.mitmproxy` and its contents so it be should allowed to assume that it has access to everything in this folder. How did you end up with wrong permissions? Expected behavior: don't crash, ideally display an error message instead but I'd say even just proceeding without writing command history is better than crashing. Chances are I ended up with this by running mitmproxy as root before - `.mitmproxy/command_history` was owned by root. I don't consider this important enough to keep this issue open, but I'd be more than happy to merge a PR that fixes this. :)
2020-11-16T21:40:58
mitmproxy/mitmproxy
4,298
mitmproxy__mitmproxy-4298
[ "3994" ]
b01d574d8b1fceae7cea10484b525301b4ba4a77
diff --git a/mitmproxy/net/tls.py b/mitmproxy/net/tls.py --- a/mitmproxy/net/tls.py +++ b/mitmproxy/net/tls.py @@ -79,43 +79,24 @@ def client_arguments_from_options(options: "mitmproxy.options.Options") -> dict: class MasterSecretLogger: def __init__(self, filename): - self.filename = filename + self.filename = os.path.expanduser(filename) self.f = None self.lock = threading.Lock() # required for functools.wraps, which pyOpenSSL uses. __name__ = "MasterSecretLogger" - def __call__(self, connection, where, ret): - done_now = ( - where == SSL.SSL_CB_HANDSHAKE_DONE and ret == 1 - ) - # this is a horrendous workaround for https://github.com/mitmproxy/mitmproxy/pull/3692#issuecomment-608454530: - # OpenSSL 1.1.1f decided to not make connection.master_key() fail in the SSL_CB_HANDSHAKE_DONE callback. - # To support various OpenSSL versions and still log master secrets, we now mark connections where this has - # happened and then try again on the next event. This is ugly and shouldn't be done, but eventually we - # replace this with context.set_keylog_callback anyways. - done_previously_but_not_logged_yet = ( - hasattr(connection, "_still_needs_masterkey") - ) - if done_now or done_previously_but_not_logged_yet: - with self.lock: - if not self.f: - d = os.path.dirname(self.filename) - if not os.path.isdir(d): - os.makedirs(d) - self.f = open(self.filename, "ab") - self.f.write(b"\r\n") - try: - client_random = binascii.hexlify(connection.client_random()) - masterkey = binascii.hexlify(connection.master_key()) - except (AssertionError, SSL.Error): # careful: exception type changes between pyOpenSSL versions - connection._still_needs_masterkey = True - else: - self.f.write(b"CLIENT_RANDOM %s %s\r\n" % (client_random, masterkey)) - self.f.flush() - if hasattr(connection, "_still_needs_masterkey"): - delattr(connection, "_still_needs_masterkey") + def __call__(self, connection, keymaterial): + with self.lock: + if not self.f: + d = os.path.dirname(self.filename) + if not os.path.isdir(d): + os.makedirs(d) + self.f = open(self.filename, "ab") + self.f.write(b"\n") + self.f.write(keymaterial) + self.f.write(b"\n") + self.f.flush() def close(self): with self.lock: @@ -203,7 +184,7 @@ def _create_ssl_context( # SSLKEYLOGFILE if log_master_secret: - context.set_info_callback(log_master_secret) + context.set_keylog_callback(log_master_secret) if alpn_protos is not None: # advertise application layer protocols diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -83,7 +83,7 @@ "passlib>=1.6.5, <1.8", "protobuf>=3.6.0, <3.14", "pyasn1>=0.3.1,<0.5", - "pyOpenSSL>=19.1.0,<19.2", + "pyOpenSSL>=20.0,<20.1", "pyparsing>=2.4.2,<2.5", "pyperclip>=1.6.0,<1.9", "ruamel.yaml>=0.16,<0.17",
diff --git a/test/mitmproxy/net/test_tls.py b/test/mitmproxy/net/test_tls.py --- a/test/mitmproxy/net/test_tls.py +++ b/test/mitmproxy/net/test_tls.py @@ -43,7 +43,7 @@ def test_log(self, tmpdir): tls.log_master_secret.close() with open(logfile, "rb") as f: - assert f.read().count(b"CLIENT_RANDOM") >= 2 + assert f.read().count(b"SERVER_HANDSHAKE_TRAFFIC_SECRET") >= 2 tls.log_master_secret = _logfun
SSLKEYLOGFILE is not containing TLSv1.3 secrets #### When using mitmproxy with the SSLKEYLOGFILE environment variable TLSv1.3 keys are not exported or correctly labeled. I want to analyze and decrypt TLSv1.3 traffic of an application with mitmproxy and Wireshark. I configured a gateway running mitmproxy in transparent mode and inside mitmproxy the traffic gets decrypted but Wireshark can not decrypt the captured data using the keylogfile provided by mitmproxy. After some research I found [this presentation](https://lekensteyn.nl/files/wireshark-tls-debugging-sharkfest19us.pdf) regarding the decryption of TLSv1.3 traffic with Wireshark. On Slide 9 there is a keylogfile example for decrypting TLSv1.3. In the keylogfile provided by mitmproxy I can't find any lines starting with CLIENT_HANDSHAKE_TRAFFIC_SECRET, CLIENT_TRAFFIC_SECRET_0 nor EXPORTER_SECRET but only ones starting with CLIENT_RANDOM. #### Steps to reproduce the behavior: 1. Export the SSLKEYLOGFILE environment variable 2. Setup mitmproxy in transparent monde 3. Open a website using TLSv1.3 4. Check the keylogfile #### System Information Mitmproxy: 5.1.1 binary Python: 3.7.6 OpenSSL: OpenSSL 1.1.1f 31 Mar 2020 Platform: Linux-5.5.0-kali2-amd64-x86_64-with-debian-kali-rolling
Thanks! We're currently waiting for upstream to expose the new OpenSSL hooks. For now the workaround is to disable 1.3 for key logging, eventually we'll support it properly. :) refs https://github.com/pyca/cryptography/pull/5187 refs https://github.com/pyca/pyopenssl/pull/910 I'm sorry for disturbing, could you please advise when you plan to fix it? https://github.com/pyca/pyopenssl/pull/910 has been merged just now, so that should not take that long…™ Looking forward to it 🤞 I'm not here to rush you (we are 1 week later now), just do you have any estimate for this fix? No estimate. I don't think I will look into that before the next pyOpenSSL release with my changes ships. I'd be more than happy to merge a PR that implements it directly on top of cryptography (the pyOpenSSL wrapper is minimal) if somebody wants to give it a stab. So 'cryptography' has had the required change since version 3.0, but we're waiting for either: * a post-19.1.0 release of pyOpenSSL * someone to step up and build the feature directly on top of cryptography, side-stepping the missing pyOpenSSL release
2020-11-19T13:41:39
mitmproxy/mitmproxy
4,333
mitmproxy__mitmproxy-4333
[ "4280" ]
d8eda8daf9a0975ed50018104604e41e897283c7
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 @@ -8,6 +8,7 @@ from mitmproxy import exceptions from mitmproxy import http from mitmproxy import flow +from mitmproxy.net.http import url from mitmproxy.proxy.protocol import base from mitmproxy.proxy.protocol.websocket import WebSocketLayer from mitmproxy.net import websockets @@ -324,7 +325,10 @@ def _process_flow(self, f): # update host header in reverse proxy mode if self.config.options.mode.startswith("reverse:") and not self.config.options.keep_host_header: - f.request.host_header = self.config.upstream_server.address[0] + f.request.host_header = url.hostport( + self.config.upstream_server.scheme, + *self.config.upstream_server.address + ) # Determine .scheme, .host and .port attributes for inline scripts. For # absolute-form requests, they are directly given in the request. For
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 @@ -452,7 +452,7 @@ def test_overridden_host_header(self): assert resp.status_code == 200 req = self.master.state.flows[0].request - assert req.host_header == "127.0.0.1" + assert req.host_header.startswith("127.0.0.1:") @pytest.mark.asyncio async def test_selfconnection(self):
map-local not working in 5.3.0 #### Problem Description We use mitmproxy locally to replay backend queries made from frontend. After updating from 5.2 to 5.3.0 every command that has the --map-local options seems to work otherwise correctly but mitmproxy seems to completely ignore the --map-local part when replaying. On startup mitmproxy does validate that the local resource is present so it doesn't completely ignore the option but it never actually seems to use it. The replay command that we use also has flows that are replayed and that part does work as intended. But even if we leave the flows out of the command and only use --map-local command the local resource is not served. #### Steps to reproduce the behavior: 1. Make a local resource file (local.json) and, optionally, prepare a flows file (mitmproxy-flows) 2. Choose a server you are trying to mimick with replay 3. Run command `mitmdump --mode reverse:http://localhost:8910/ -S mitmproxy-flows --server-replay-nopop --server-replay-refresh --listen-port 7777 --map-local "|~m GET|localhost:8910/api/resource|local.json"` 4. Try to go to URL http://localhost:7777/api/resource #### System Information WORKING version info is: ``` Mitmproxy: 5.2 binary Python: 3.7.8 OpenSSL: OpenSSL 1.1.1g 21 Apr 2020 Platform: Darwin-19.6.0-x86_64-i386-64bit ``` (note that I used the macOS binaries here when testing with 5.2 but it was also working with 5.2 installed with homebrew) NOT WORKING version info is: ``` Mitmproxy: 5.3.0 Python: 3.9.0 OpenSSL: OpenSSL 1.1.1h 22 Sep 2020 Platform: macOS-10.15.7-x86_64-i386-64bit ```
@mplattner, can you reproduce this? Any update to this? This is currently forcing the team to stay in the previous version and I guess I will downgrade too. While I understand that non-reproduced bugs are not main priority to you but for us this is certain (reproduced on separate machines) problem. @mhils could you at least confirm that there has not been changes in map-local syntax between 5.2 and 5.3.0? We do not see any changes in documentation at least. Of course there might be more pressing bugs to fix too so I will not complain but I just hope that at least in some version in the future this issue is fixed so that we can continue using the latest version of mitmproxy. Another comment about versions in homebrew. For two people in our team homebrew decided to do housekeeping and updated mitmproxy version number without consent. That would not be a problem if homebrew would have kept the old version locally OR if the old version would still be available to download in the net. Alas neither of these is true. So for those two people the only option is to use the docker images or the precompiled binaries. Seems rather strange but I guess this is one of those things that can not be helped. @Krakau: Thanks for the very polite bugging. :) I'll try to squeeze this in somewhere tomorrow. Regarding your questions: We didn't even touch the map local addon between 5.2 and 5.3, so no syntax changes: https://github.com/mitmproxy/mitmproxy/commits/master/mitmproxy/addons/maplocal.py So this is a bit of a curious case anyway. :-) > Another comment about versions in homebrew. [...] There's not much we can do on the homebrew front (we do very much appreciate how quick they update if we publish releases though). You can get old standalone binaries at https://mitmproxy.org/downloads/, you can use `pipx`, or you can use the Docker images. Doesn't that qualify as "the old version is still available to download in the net"? What else would you be looking for? Ok, it looks like I can reproduce this now. The first bad commit is 46fbba639dd3581fa427db6d2.
2020-12-10T08:01:53
mitmproxy/mitmproxy
4,334
mitmproxy__mitmproxy-4334
[ "4312" ]
d8eda8daf9a0975ed50018104604e41e897283c7
diff --git a/mitmproxy/addons/modifyheaders.py b/mitmproxy/addons/modifyheaders.py --- a/mitmproxy/addons/modifyheaders.py +++ b/mitmproxy/addons/modifyheaders.py @@ -63,8 +63,8 @@ def load(self, loader): ) def configure(self, updated): - self.replacements = [] if "modify_headers" in updated: + self.replacements = [] for option in ctx.options.modify_headers: try: spec = parse_modify_spec(option, False)
Mitmdump option "--modify-headers" not working if any script added using "--scripts". #### Problem Description When using mitmdump with script specified using `--scripts` option - `--modify-headers` option is ignored. #### Steps to reproduce the behavior: **1.** Launch `mitmdump` with `--modify-headers`. My example: `mitmdump --set confdir=./.mitmproxy --flow-detail=2 --listen-port=8081 --modify-headers "/~q/Host/example.org"` Output with `curl -x 127.0.0.1:8081 "http://www.trackip.net/ip?json"`: ``` 127.0.0.1:50216: clientconnect 127.0.0.1:50216: GET http://www.trackip.net/ip?json User-Agent: curl/7.64.1 Accept: */* Proxy-Connection: Keep-Alive Host: example.org << 404 Not Found 1.67k Date: Thu, 26 Nov 2020 10:06:22 GMT Content-Type: text/html; charset=UTF-8 Transfer-Encoding: chunked Connection: keep-alive Set-Cookie: __cfduid=de786483d16a417b8768b01f604ef7f991606385181; expires=Sat, 26-Dec-20 10:06:21 GMT; path=/; domain=.example.org; HttpOnly; SameSite=Lax Lookup-Cache-Hit: 1 Cache-Control: public, max-age=60 Vary: Accept-Language, Accept-Encoding X-Cache: MISS X-Cache-Hits: 0 CF-Cache-Status: MISS cf-request-id: 06a59dbd0500002d377c038000000001 Report-To: {"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report?s=NYIz48uJ3L6ZWGjd%2FEO4iNMvcCH0gsGhQhs4dpQ92t5e7W2I3wP1hp%2FoVqfbe94xjJbxqsuNcuvGp4dShFlFYVyn3W0hQX6RveNgJw%3D%3D"}],"group":"cf-nel","max_age":604800} NEL: {"report_to":"cf-nel","max_age":604800} X-Content-Type-Options: nosniff Server: cloudflare CF-RAY: 5f82cbdb3f422d37-KBP 127.0.0.1:50216: clientdisconnect ``` Header `Host` has been replaced with `example.org`, as expected. **2.** Now launch `mitmdump` with `--modify-headers` and `--script`. My example (using [jsondump.py](https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/jsondump.py) script from `examples/contrib`): `mitmdump --set confdir=./.mitmproxy --flow-detail=2 --listen-port=8081 --modify-headers "/~q/Host/example.org" --scripts="/Users/ignisor/dev/proxy_lib/proxy/utils/jsondump.py"` Output with `curl -x 127.0.0.1:8081 "http://www.trackip.net/ip?json"`: ``` Proxy server listening at http://*:8081 127.0.0.1:50412: clientconnect 127.0.0.1:50412: GET http://www.trackip.net/ip?json Host: www.trackip.net User-Agent: curl/7.64.1 Accept: */* Proxy-Connection: Keep-Alive << 200 OK 76b Date: Thu, 26 Nov 2020 10:11:30 GMT Content-Type: text/plain Content-Length: 76 Connection: keep-alive Set-Cookie: __cfduid=dd9e78e478768657490d8e5f8df1e870d1606385490; expires=Sat, 26-Dec-20 10:11:30 GMT; path=/; domain=.trackip.net; HttpOnly; SameSite=Lax CF-Cache-Status: DYNAMIC cf-request-id: 06a5a272a300003f0495bde000000001 Report-To: {"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report?s=E3IAN%2BfUeGUIqX75SqBx%2FwUVisP1%2Fa7iRdHS7P6wUzZI1A6zSkhSqR6sKJ82sZo9tWkzTrtPYVQq6xozPGJ82Y34hSyPXP%2Fo%2FW7kC%2FFulUc%3D"}],"group":"cf-nel","max_age":604800} NEL: {"report_to":"cf-nel","max_age":604800} Server: cloudflare CF-RAY: 5f82d3643d183f04-KBP 127.0.0.1:50412: clientdisconnect ``` Header `Host` **not changed** and still `www.trackip.net`. #### System Information > Mitmproxy: 5.3.0 > Python: 3.9.0 > OpenSSL: OpenSSL 1.1.1h 22 Sep 2020 > Platform: macOS-10.16-x86_64-i386-64bit
Thanks! This seems to affect addons which call `loader.add_option`. Minimal example: ``` # Good $ mitmdump --modify-headers "/~q/Host/example.org" # Bad $ mitmdump --modify-headers "/~q/Host/example.org" --scripts examples/addons/options-simple.py $ curl -x 127.0.0.1:8080 "http://www.trackip.net/ip?json" ```
2020-12-10T08:55:16
mitmproxy/mitmproxy
4,439
mitmproxy__mitmproxy-4439
[ "3855" ]
856a35af6dee32090765ec0f5de0573ef63db4dd
diff --git a/examples/contrib/har_dump.py b/examples/contrib/har_dump.py --- a/examples/contrib/har_dump.py +++ b/examples/contrib/har_dump.py @@ -20,7 +20,7 @@ import mitmproxy -from mitmproxy import connections # noqa +from mitmproxy import connection from mitmproxy import version from mitmproxy import ctx from mitmproxy.utils import strutils @@ -30,7 +30,7 @@ # A list of server seen till now is maintained so we can avoid # using 'connect' time for entries that use an existing connection. -SERVERS_SEEN: typing.Set[connections.ServerConnection] = set() +SERVERS_SEEN: typing.Set[connection.Server] = set() def load(l): @@ -53,7 +53,7 @@ def configure(updated): }) -def response(flow): +def response(flow: mitmproxy.http.HTTPFlow): """ Called when a server response has been received. """ @@ -153,7 +153,7 @@ def response(flow): "params": params } - if flow.server_conn.connected(): + if flow.server_conn.connected: entry["serverIPAddress"] = str(flow.server_conn.ip_address[0]) HAR["log"]["entries"].append(entry)
diff --git a/examples/contrib/test_har_dump.py b/examples/contrib/test_har_dump.py --- a/examples/contrib/test_har_dump.py +++ b/examples/contrib/test_har_dump.py @@ -20,12 +20,18 @@ def flow(self, resp_content=b'message'): ) def test_simple(self, tmpdir, tdata): + # context is needed to provide ctx.log function that + # is invoked if there are exceptions with taddons.context() as tctx: a = tctx.script(tdata.path("../examples/contrib/har_dump.py")) + # check script is read without errors + assert tctx.master.logs == [] + assert a.name_value # last function in har_dump.py + path = str(tmpdir.join("somefile")) tctx.configure(a, hardump=path) - tctx.invoke(a, "response", self.flow()) - tctx.invoke(a, "done") + a.response(self.flow()) + a.done() with open(path) as inp: har = json.load(inp) assert len(har["log"]["entries"]) == 1 @@ -36,10 +42,8 @@ def test_base64(self, tmpdir, tdata): path = str(tmpdir.join("somefile")) tctx.configure(a, hardump=path) - tctx.invoke( - a, "response", self.flow(resp_content=b"foo" + b"\xFF" * 10) - ) - tctx.invoke(a, "done") + a.response(self.flow(resp_content=b"foo" + b"\xFF" * 10)) + a.done() with open(path) as inp: har = json.load(inp) assert har["log"]["entries"][0]["response"]["content"]["encoding"] == "base64" @@ -76,8 +80,8 @@ def test_binary(self, tmpdir, tdata): f.response.headers["random-junk"] = bytes(range(256)) f.response.content = bytes(range(256)) - tctx.invoke(a, "response", f) - tctx.invoke(a, "done") + a.response(f) + a.done() with open(path) as inp: har = json.load(inp)
HAR file does not appears when I try to use har_dump.py script HAR file does not appears when I try to use har_dump.py script calling from command line Steps to reproduce the behavior: 1. Type **mitmdump -s har_dump.py --set hardump=dump.har** 2. Press Enter 3. Do something in browser via proxy 4. Press Ctr+C File dump.har doesn't present in my hard disc at all System Information: Mitmproxy: 5.0.1 Python: 3.6.3 OpenSSL: OpenSSL 1.1.0j 20 Nov 2018 Platform: Windows-10-10.0.18362-SP0
I'm having the same problem. Mitmproxy:6.0.0.dev python3.7.7 Platform:win10 I suspect it's the Windows console, ctrl+c causes def done not to execute Duplicate of #3377.
2021-02-11T10:22:15
mitmproxy/mitmproxy
4,446
mitmproxy__mitmproxy-4446
[ "4416" ]
9763c1810d7279cf56bb001a7d622069d4b2092d
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 @@ -111,7 +111,7 @@ def _read_request_line(line: bytes) -> Tuple[str, int, bytes, bytes, bytes, byte raise ValueError else: scheme, rest = target.split(b"://", maxsplit=1) - authority, path_ = rest.split(b"/", maxsplit=1) + authority, _, path_ = rest.partition(b"/") path = b"/" + path_ host, port = url.parse_authority(authority, check=True) port = port or url.default_port(scheme)
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 @@ -137,6 +137,8 @@ def t(b): ("foo", 42, b"CONNECT", b"", b"foo:42", b"", b"HTTP/1.1")) assert (t(b"GET http://foo:42/bar HTTP/1.1") == ("foo", 42, b"GET", b"http", b"foo:42", b"/bar", b"HTTP/1.1")) + assert (t(b"GET http://foo:42 HTTP/1.1") == + ("foo", 42, b"GET", b"http", b"foo:42", b"/", b"HTTP/1.1")) with pytest.raises(ValueError): t(b"GET / WTF/1.1")
Omitting a forward slash from http domain produces Bad HTTP request line #### Problem Description Running a GET request for "http://wikipedia.com" will produce the following output: `35.176.198.120:43784: clientconnect << Bad HTTP request line: b'GET http://wikipedia.com HTTP/1.1' ::ffff:35.176.198.120:43784: request -> HTTP protocol error in client request: Bad HTTP request line: b'GET http://wikipedia.com HTTP/1.1' 35.176.198.120:43784: clientdisconnect` The request status, headers and body are as follows for the client: `400 <CIMultiDictProxy('Server': 'mitmproxy 5.3.0', 'Connection': 'close', 'Content-Length': '306', 'Content-Type': 'text/html')> b'<html>\n <head>\n <title>400 Bad Request</title>\n </head>\n <body>\n <h1>400 Bad Request</h1>\n <p>HttpSyntaxException(&quot;Bad HTTP request line: b&#x27;GET http://wikipedia.com HTTP/1.1&#x27;&quot;)</p>\n </body>\n </html>` Running a GET request for "http://wikipedia.com/" will not produce this error. Nor will "https://wikipedia.com". Curl runs the problematic URL fine as it appends the missing trailing slash before running the request which can be seen by printing flow.request.url. #### Steps to reproduce the behavior: 1. Start mitmproxy using "mitmdump -s proxy_server.py --set block_global=false" 2. Run a GET request with mitm proxy as the request proxy for "http://wikipedia.com". #### System Information Mitmproxy: 5.3.0 Python: 3.7.9 OpenSSL: OpenSSL 1.1.1h 22 Sep 2020 Platform: Linux-4.14.203-156.332.amzn2.x86_64-x86_64-with-glibc2.2.5
Thanks, I can reproduce this on master. Fixes welcome! Hey, @mhils! I'd like to take this issue. I'm expecting to send a PR this week. Hey, @mhils! I've done some research on the topic: [HTTP 1.1 spec](https://tools.ietf.org/html/rfc2616#section-5.1.2) says that Request-Line `GET http://wikipedia.com HTTP/1.1` is actually a malformed one: ```Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root).``` It also says: ```A transparent proxy MUST NOT rewrite the "abs_path" part of the received Request-URI when forwarding it to the next inbound server, except as noted above to replace a null abs_path with "/".``` Having this, I think we should fix it by appending a "/" to request URI when it doesn't have one. What are your thoughts? This generally sounds good to me. Have you checked if there is more current guidance in any of the 72xx HTTP RFCs?
2021-02-13T15:50:06
mitmproxy/mitmproxy
4,454
mitmproxy__mitmproxy-4454
[ "4452", "4452" ]
aebc40c408730e6e6113bf364d6f741dfda00740
diff --git a/mitmproxy/proxy/layers/http/_http2.py b/mitmproxy/proxy/layers/http/_http2.py --- a/mitmproxy/proxy/layers/http/_http2.py +++ b/mitmproxy/proxy/layers/http/_http2.py @@ -64,11 +64,29 @@ def __init__(self, context: Context, conn: Connection): def is_closed(self, stream_id: int) -> bool: """Check if a non-idle stream is closed""" stream = self.h2_conn.streams.get(stream_id, None) - if stream is not None: - return stream.closed + if ( + stream is not None + and + stream.state_machine.state is not h2.stream.StreamState.CLOSED + ): + return False else: return True + def is_open_for_us(self, stream_id: int) -> bool: + """Check if we can write to a non-idle stream.""" + stream = self.h2_conn.streams.get(stream_id, None) + if ( + stream is not None + and + stream.state_machine.state is not h2.stream.StreamState.HALF_CLOSED_LOCAL + and + stream.state_machine.state is not h2.stream.StreamState.CLOSED + ): + return True + else: + return False + def _handle_event(self, event: Event) -> CommandGenerator[None]: if isinstance(event, Start): self.h2_conn.initiate_connection() @@ -77,24 +95,18 @@ def _handle_event(self, event: Event) -> CommandGenerator[None]: elif isinstance(event, HttpEvent): if isinstance(event, self.SendData): assert isinstance(event, (RequestData, ResponseData)) - self.h2_conn.send_data(event.stream_id, event.data) + if self.is_open_for_us(event.stream_id): + self.h2_conn.send_data(event.stream_id, event.data) elif isinstance(event, self.SendEndOfMessage): - stream = self.h2_conn.streams.get(event.stream_id) - if stream.state_machine.state not in (h2.stream.StreamState.HALF_CLOSED_LOCAL, - h2.stream.StreamState.CLOSED): + if self.is_open_for_us(event.stream_id): self.h2_conn.end_stream(event.stream_id) - if self.is_closed(event.stream_id): - self.streams.pop(event.stream_id, None) elif isinstance(event, self.SendProtocolError): assert isinstance(event, (RequestProtocolError, ResponseProtocolError)) - stream = self.h2_conn.streams.get(event.stream_id) - if stream.state_machine.state is not h2.stream.StreamState.CLOSED: + if not self.is_closed(event.stream_id): code = { status_codes.CLIENT_CLOSED_REQUEST: h2.errors.ErrorCodes.CANCEL, }.get(event.code, h2.errors.ErrorCodes.INTERNAL_ERROR) self.h2_conn.reset_stream(event.stream_id, code) - if self.is_closed(event.stream_id): - self.streams.pop(event.stream_id, None) else: raise AssertionError(f"Unexpected event: {event}") data_to_send = self.h2_conn.data_to_send() @@ -250,18 +262,19 @@ def __init__(self, context: Context): def _handle_event(self, event: Event) -> CommandGenerator[None]: if isinstance(event, ResponseHeaders): - headers = [ - (b":status", b"%d" % event.response.status_code), - *event.response.headers.fields - ] - if not event.response.is_http2: - headers = normalize_h1_headers(headers, False) - - self.h2_conn.send_headers( - event.stream_id, - headers, - ) - yield SendData(self.conn, self.h2_conn.data_to_send()) + if self.is_open_for_us(event.stream_id): + headers = [ + (b":status", b"%d" % event.response.status_code), + *event.response.headers.fields + ] + if not event.response.is_http2: + headers = normalize_h1_headers(headers, False) + + self.h2_conn.send_headers( + event.stream_id, + headers, + ) + yield SendData(self.conn, self.h2_conn.data_to_send()) else: yield from super()._handle_event(event)
Crash when proxying HTTP/2 #### Problem Description Looks like we have a bug in our HTTP/2 code: #### Steps to reproduce the behavior: 1. `mitmdump --set proxy_debug -vvv` 3. Browse openstreetmap.org with Firefox ``` 127.0.0.1:49187: mitmproxy has crashed! Traceback (most recent call last): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 570, in _handle_event yield from self.event_to_child(stream, event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 586, in event_to_child for command in child.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 488, in passthrough for command in self.child_layer.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 570, in _handle_event yield from self.event_to_child(stream, event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 601, in event_to_child yield from self.event_to_child(conn, command.event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 586, in event_to_child for command in child.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 123, in __process command = command_generator.send(send) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/_http2.py", line 266, in _handle_event yield from super()._handle_event(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/_http2.py", line 91, in _handle_event if stream.state_machine.state is not h2.stream.StreamState.CLOSED: AttributeError: 'NoneType' object has no attribute 'state_machine' ``` #### System Information ``` Mitmproxy: 7.0.0.dev (+330, commit b5d9dcd) Python: 3.9.1 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-4.4.0-19041-Microsoft-x86_64-with-glibc2.27 ``` Crash when proxying HTTP/2 #### Problem Description Looks like we have a bug in our HTTP/2 code: #### Steps to reproduce the behavior: 1. `mitmdump --set proxy_debug -vvv` 3. Browse openstreetmap.org with Firefox ``` 127.0.0.1:49187: mitmproxy has crashed! Traceback (most recent call last): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 570, in _handle_event yield from self.event_to_child(stream, event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 586, in event_to_child for command in child.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 488, in passthrough for command in self.child_layer.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 570, in _handle_event yield from self.event_to_child(stream, event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 601, in event_to_child yield from self.event_to_child(conn, command.event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 586, in event_to_child for command in child.handle_event(event): File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layer.py", line 123, in __process command = command_generator.send(send) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/_http2.py", line 266, in _handle_event yield from super()._handle_event(event) File "/mnt/c/Users/user/git/mitmproxy/mitmproxy/proxy/layers/http/_http2.py", line 91, in _handle_event if stream.state_machine.state is not h2.stream.StreamState.CLOSED: AttributeError: 'NoneType' object has no attribute 'state_machine' ``` #### System Information ``` Mitmproxy: 7.0.0.dev (+330, commit b5d9dcd) Python: 3.9.1 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-4.4.0-19041-Microsoft-x86_64-with-glibc2.27 ```
2021-02-16T16:32:38
mitmproxy/mitmproxy
4,488
mitmproxy__mitmproxy-4488
[ "4487", "4487", "4487" ]
6d9f00408c489b9f9e8bf7a9dbf6ac02f271faa0
diff --git a/mitmproxy/proxy/layers/http/__init__.py b/mitmproxy/proxy/layers/http/__init__.py --- a/mitmproxy/proxy/layers/http/__init__.py +++ b/mitmproxy/proxy/layers/http/__init__.py @@ -376,7 +376,7 @@ def handle_protocol_error( is_client_error_but_we_already_talk_upstream = ( isinstance(event, RequestProtocolError) and self.client_state in (self.state_stream_request_body, self.state_done) - and self.server_state != self.state_errored + and self.server_state not in (self.state_done, self.state_errored) ) need_error_hook = not ( self.client_state in (self.state_wait_for_request_headers, self.state_errored)
Reply from proxy causes Mitmproxy crash #### Problem Description #### Steps to reproduce the behavior: ```python from mitmproxy import http class MrCrash: def request(self, flow: http.HTTPFlow) -> None: flow.response = http.Response.make(407) addons = [ MrCrash() ] ``` Execute `ALL_PROXY="http://0.0.0.0:8080" curl -vvv -k https://ironpeak.be/` And in the logs: ``` info: Loading script scripts/crash.py info: Proxy server listening at http://*:8080 info: 172.17.0.1:58468: client connect error: 172.17.0.1:58468: mitmproxy has crashed! Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 590, in event_to_child for command in child.handle_event(event): ⇩ [1/1] [scripts:1] [*:8080] Error: 172.17.0.1:58468: mitmproxy has crashed!(more in eventlog) ``` #### System Information ```shell mitmproxy --version Mitmproxy: 7.0.0.dev Python: 3.9.2 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-4.19.121-linuxkit-aarch64-with-glibc2.28 ``` Reply from proxy causes Mitmproxy crash #### Problem Description #### Steps to reproduce the behavior: ```python from mitmproxy import http class MrCrash: def request(self, flow: http.HTTPFlow) -> None: flow.response = http.Response.make(407) addons = [ MrCrash() ] ``` Execute `ALL_PROXY="http://0.0.0.0:8080" curl -vvv -k https://ironpeak.be/` And in the logs: ``` info: Loading script scripts/crash.py info: Proxy server listening at http://*:8080 info: 172.17.0.1:58468: client connect error: 172.17.0.1:58468: mitmproxy has crashed! Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 590, in event_to_child for command in child.handle_event(event): ⇩ [1/1] [scripts:1] [*:8080] Error: 172.17.0.1:58468: mitmproxy has crashed!(more in eventlog) ``` #### System Information ```shell mitmproxy --version Mitmproxy: 7.0.0.dev Python: 3.9.2 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-4.19.121-linuxkit-aarch64-with-glibc2.28 ``` Reply from proxy causes Mitmproxy crash #### Problem Description #### Steps to reproduce the behavior: ```python from mitmproxy import http class MrCrash: def request(self, flow: http.HTTPFlow) -> None: flow.response = http.Response.make(407) addons = [ MrCrash() ] ``` Execute `ALL_PROXY="http://0.0.0.0:8080" curl -vvv -k https://ironpeak.be/` And in the logs: ``` info: Loading script scripts/crash.py info: Proxy server listening at http://*:8080 info: 172.17.0.1:58468: client connect error: 172.17.0.1:58468: mitmproxy has crashed! Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 590, in event_to_child for command in child.handle_event(event): ⇩ [1/1] [scripts:1] [*:8080] Error: 172.17.0.1:58468: mitmproxy has crashed!(more in eventlog) ``` #### System Information ```shell mitmproxy --version Mitmproxy: 7.0.0.dev Python: 3.9.2 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-4.19.121-linuxkit-aarch64-with-glibc2.28 ```
Thanks for the detailed info. I can reproduce this with the latest master and the [official example](https://github.com/mitmproxy/mitmproxy/blob/6d9f00408c489b9f9e8bf7a9dbf6ac02f271faa0/examples/addons/http-reply-from-proxy.py) when updating it to HTTPS ```py """Send a reply from the proxy without sending any data to the remote server.""" from mitmproxy import http def request(flow: http.HTTPFlow) -> None: if flow.request.pretty_url == "https://example.com/path": flow.response = http.Response.make( 200, # (optional) status code b"Hello World", # (optional) content {"Content-Type": "text/html"} # (optional) headers ) ``` The response however is successfully delivered to curl. Full stack ``` Traceback (most recent call last): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 590, in event_to_child for command in child.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 492, in passthrough for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 72, in _handle_event yield from self.receive_data(event.data) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 246, in receive_data yield from self.event_to_child( File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 604, in event_to_child conn = self.connections[command.connection] KeyError: Server({'id': '…cd155e', 'address': ('example.com', 443), 'state': <ConnectionState.CLOSED: 0>, 'tls': True}) ``` Thanks for the detailed info. I can reproduce this with the latest master and the [official example](https://github.com/mitmproxy/mitmproxy/blob/6d9f00408c489b9f9e8bf7a9dbf6ac02f271faa0/examples/addons/http-reply-from-proxy.py) when updating it to HTTPS ```py """Send a reply from the proxy without sending any data to the remote server.""" from mitmproxy import http def request(flow: http.HTTPFlow) -> None: if flow.request.pretty_url == "https://example.com/path": flow.response = http.Response.make( 200, # (optional) status code b"Hello World", # (optional) content {"Content-Type": "text/html"} # (optional) headers ) ``` The response however is successfully delivered to curl. Full stack ``` Traceback (most recent call last): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 590, in event_to_child for command in child.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 492, in passthrough for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 72, in _handle_event yield from self.receive_data(event.data) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 246, in receive_data yield from self.event_to_child( File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 604, in event_to_child conn = self.connections[command.connection] KeyError: Server({'id': '…cd155e', 'address': ('example.com', 443), 'state': <ConnectionState.CLOSED: 0>, 'tls': True}) ``` Thanks for the detailed info. I can reproduce this with the latest master and the [official example](https://github.com/mitmproxy/mitmproxy/blob/6d9f00408c489b9f9e8bf7a9dbf6ac02f271faa0/examples/addons/http-reply-from-proxy.py) when updating it to HTTPS ```py """Send a reply from the proxy without sending any data to the remote server.""" from mitmproxy import http def request(flow: http.HTTPFlow) -> None: if flow.request.pretty_url == "https://example.com/path": flow.response = http.Response.make( 200, # (optional) status code b"Hello World", # (optional) content {"Content-Type": "text/html"} # (optional) headers ) ``` The response however is successfully delivered to curl. Full stack ``` Traceback (most recent call last): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 186, in handle_event yield from self._handle(event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 590, in event_to_child for command in child.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 492, in passthrough for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 72, in _handle_event yield from self.receive_data(event.data) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 246, in receive_data yield from self.event_to_child( File "/home/alex/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 104, in event_to_child for command in self.child_layer.handle_event(event): File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 114, in handle_event yield from self.__process(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layer.py", line 142, in __process command = next(command_generator) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 581, in _handle_event yield from self.event_to_child(handler, event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 602, in event_to_child yield from self.event_to_child(stream, command.event) File "/home/alex/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 604, in event_to_child conn = self.connections[command.connection] KeyError: Server({'id': '…cd155e', 'address': ('example.com', 443), 'state': <ConnectionState.CLOSED: 0>, 'tls': True}) ```
2021-03-09T16:49:05
mitmproxy/mitmproxy
4,532
mitmproxy__mitmproxy-4532
[ "4525" ]
338cd0b00a007b9b0802e3bd78fbc4200b5be187
diff --git a/mitmproxy/options.py b/mitmproxy/options.py --- a/mitmproxy/options.py +++ b/mitmproxy/options.py @@ -47,7 +47,12 @@ def __init__(self, **kwargs) -> None: ) self.add_option( "cert_passphrase", Optional[str], None, - "Passphrase for decrypting the private key provided in the --cert option." + """ + Passphrase for decrypting the private key provided in the --cert option. + + Note that passing cert_passphrase on the command line makes your passphrase visible in your system's + process list. Specify it in config.yaml to avoid this. + """ ) self.add_option( "ciphers_client", Optional[str], None,
Passphrase given in the command line is visible in the process list #### Problem Description Mitmproxy accepts cert-passphrase as one of the command-line options. If the user gives a passphrase like this while running the mitmproxy, anyone having access to a command line on that server can see the passphrase by listing the running processes. #### Steps to reproduce the behavior: 1. Create a self-signed certificate using openssl, make sure you give a passphrase for the certificate. 2. Run mitmproxy/mitmdump/mitmweb with the command line options as shown mitmdump --certs *.mydomain.com=mycert.pem cert-passphrase abcd 3. Take a Linux terminal and issue the command ps -ef | grep mitm 4. You can see the passphrase given to mitmdump command in clear text This is a security issue in my opinion. Some programs effectively hide such sensitive inputs that are given as command-line arguments. They do this by rewriting the command line args in an obfuscated manner and by rerunning the program by itself. In this way, the sensitive data that came along via command-line arguments will be visible for a split second, but that is still better than making them always visible as long as the program is running.
Thanks for raising this! This is an issue if you are running mitmproxy with a custom cert passphrase passed via the command line on a system where an adversary may be able to access the process table. To avoid this, you can specify cert_passphrase in `config.yaml` (https://docs.mitmproxy.org/stable/concepts-options/) or use an unencrypted certificate. What alternative do you suggest? Rewriting the command line args increases complexity while not solving the issue but only making it slightly harder to exploit. Passing secrets as environment variables introduces its own set of issues. The only realistic options I can think of are: 1. We can change the option to read a file containing the password, but that's really quite cumbersome and brings up the question why you don't decrypt the certificate in the first place. It also works really badly for people who use `config.yaml`. 2. We can add a note in the option description. I don't know how easily this could be done with the mitmproxy architecture and it's most likely not worth the effort for the gains, but couldn't mitmproxy ask for the password? So if the argument is given it will say "Please enter passphrase:" and only actually start after that. > This is a security issue in my opinion. Some programs effectively hide such sensitive inputs that are given as command-line arguments. They do this by rewriting the command line args in an obfuscated manner and by rerunning the program by itself. In this way, the sensitive data that came along via command-line arguments will be visible for a split second, but that is still better than making them always visible as long as the program is running. What about `.bash_history` or an equivalent? In your (hypothetical) server scenario, does the malicious user has permissions to see _other users'_ processes but cannot read other users files? I'm honestly not sure how this is handled in Linux. Edit: > will be visible for a split second This sounds an awful lot like security by obscurity because it _feels_ more secure to a human. Can you link to some sources? I'm legit curious if and how this is actually done in the wild and what the threat model looks like.
2021-03-30T07:47:53
mitmproxy/mitmproxy
4,557
mitmproxy__mitmproxy-4557
[ "4555" ]
c6ba97eab699b326f27c68cc85a97e2848e8f564
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py --- a/mitmproxy/certs.py +++ b/mitmproxy/certs.py @@ -145,8 +145,13 @@ def altnames(self) -> List[str]: def _name_to_keyval(name: x509.Name) -> List[Tuple[str, str]]: parts = [] - for rdn in name.rdns: - k, v = rdn.rfc4514_string().split("=", maxsplit=1) + for attr in name: + # pyca cryptography <35.0.0 backwards compatiblity + if hasattr(name, "rfc4514_attribute_name"): # pragma: no cover + k = attr.rfc4514_attribute_name # type: ignore + else: # pragma: no cover + k = attr.rfc4514_string().partition("=")[0] + v = attr.value parts.append((k, v)) return parts
diff --git a/test/mitmproxy/net/data/text_cert_with_comma b/test/mitmproxy/net/data/text_cert_with_comma new file mode 100644 --- /dev/null +++ b/test/mitmproxy/net/data/text_cert_with_comma @@ -0,0 +1,29 @@ +-----BEGIN CERTIFICATE----- +MIIFBjCCBK2gAwIBAgIQDovzdw2S0Zbwu2H5PEFmvjAKBggqhkjOPQQDAjBnMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xPzA9BgNVBAMTNkRp +Z2lDZXJ0IEhpZ2ggQXNzdXJhbmNlIFRMUyBIeWJyaWQgRUNDIFNIQTI1NiAyMDIw +IENBMTAeFw0yMTAzMjUwMDAwMDBaFw0yMjAzMzAyMzU5NTlaMGYxCzAJBgNVBAYT +AlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2Nv +MRUwEwYDVQQKEwxHaXRIdWIsIEluYy4xEzARBgNVBAMTCmdpdGh1Yi5jb20wWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAASt9vd1sdNJVApdEHG93CUGSyIcoiNOn6H+ +udCMvTm8DCPHz5GmkFrYRasDE77BI3q5xMidR/aW4Ll2a1A2ZvcNo4IDOjCCAzYw +HwYDVR0jBBgwFoAUUGGmoNI1xBEqII0fD6xC8M0pz0swHQYDVR0OBBYEFCexfp+7 +JplQ2PPDU1v+MRawux5yMCUGA1UdEQQeMByCCmdpdGh1Yi5jb22CDnd3dy5naXRo +dWIuY29tMA4GA1UdDwEB/wQEAwIHgDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB +BQUHAwIwgbEGA1UdHwSBqTCBpjBRoE+gTYZLaHR0cDovL2NybDMuZGlnaWNlcnQu +Y29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZVRMU0h5YnJpZEVDQ1NIQTI1NjIwMjBD +QTEuY3JsMFGgT6BNhktodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGlnaUNlcnRI +aWdoQXNzdXJhbmNlVExTSHlicmlkRUNDU0hBMjU2MjAyMENBMS5jcmwwPgYDVR0g +BDcwNTAzBgZngQwBAgIwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2Vy +dC5jb20vQ1BTMIGSBggrBgEFBQcBAQSBhTCBgjAkBggrBgEFBQcwAYYYaHR0cDov +L29jc3AuZGlnaWNlcnQuY29tMFoGCCsGAQUFBzAChk5odHRwOi8vY2FjZXJ0cy5k +aWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNzdXJhbmNlVExTSHlicmlkRUNDU0hB +MjU2MjAyMENBMS5jcnQwDAYDVR0TAQH/BAIwADCCAQUGCisGAQQB1nkCBAIEgfYE +gfMA8QB2ACl5vvCeOTkh8FZzn2Old+W+V32cYAr4+U1dJlwlXceEAAABeGq/vRoA +AAQDAEcwRQIhAJ7miER//DRFnDJNn6uUhgau3WMt4vVfY5dGigulOdjXAiBIVCfR +xjK1v4F31+sVaKzyyO7JAa0fzDQM7skQckSYWQB3ACJFRQdZVSRWlj+hL/H3bYbg +IyZjrcBLf13Gg1xu4g8CAAABeGq/vTkAAAQDAEgwRgIhAJgAEkoJQRivBlwo7x67 +3oVsf1ip096WshZqmRCuL/JpAiEA3cX4rb3waLDLq4C48NSoUmcw56PwO/m2uwnQ +prb+yh0wCgYIKoZIzj0EAwIDRwAwRAIgK+Kv7G+/KkWkNZg3PcQFp866Z7G6soxo +a4etSZ+SRlYCIBSiXS20Wc+yjD111nPzvQUCfsP4+DKZ3K+2GKsERD6d +-----END CERTIFICATE----- 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 @@ -1,5 +1,7 @@ import os from pathlib import Path +from cryptography import x509 +from cryptography.x509 import NameOID import pytest @@ -231,3 +233,26 @@ def test_from_store_with_passphrase(self, tdata, tstore): with pytest.raises(TypeError): tstore.add_cert_file("encrypted-no-pass", Path(tdata.path("mitmproxy/data/mitmproxy.pem")), None) + + def test_special_character(self, tdata): + with open(tdata.path("mitmproxy/net/data/text_cert_with_comma"), "rb") as f: + d = f.read() + c = certs.Cert.from_pem(d) + + assert dict(c.issuer).get('O') == 'DigiCert, Inc.' + assert dict(c.subject).get('O') == 'GitHub, Inc.' + + def test_multi_valued_rdns(self, tdata): + subject = x509.Name([ + x509.RelativeDistinguishedName([ + x509.NameAttribute(NameOID.TITLE, u'Test'), + x509.NameAttribute(NameOID.COMMON_NAME, u'Multivalue'), + x509.NameAttribute(NameOID.SURNAME, u'RDNs'), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'TSLA'), + ]), + x509.RelativeDistinguishedName([ + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA') + ]), + ]) + expected = [('2.5.4.12', 'Test'), ('CN', 'Multivalue'), ('2.5.4.4', 'RDNs'), ('O', 'TSLA'), ('O', 'PyCA')] + assert(certs._name_to_keyval(subject)) == expected
v7: Cert issuer/subject values contain escapes sequences #### Problem Description Escape sequence is not the proper term I guess. I've noticed that commas are prefixed with a backslash. #### Steps to reproduce the behavior: ```py def server_disconnected(data): server = data.server cert = (server.certificate_list[0] if server.certificate_list else None) if cert: print(dict(cert.issuer).get('O')) ``` `mitmdump --quiet --scripts cert.py` `curl --proxy "localhost:8080" https://www.github.com` ``` DigiCert\, Inc. ``` #### System Information ``` Mitmproxy: 7.0.0.dev (+421, commit 72b00b5) Python: 3.8.5 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-5.8.0-48-generic-x86_64-with-glibc2.29 ```
2021-04-08T16:12:43
mitmproxy/mitmproxy
4,594
mitmproxy__mitmproxy-4594
[ "4551" ]
518fb941242101a4407a46f9ad4bb95122a374c9
diff --git a/mitmproxy/proxy/layers/tls.py b/mitmproxy/proxy/layers/tls.py --- a/mitmproxy/proxy/layers/tls.py +++ b/mitmproxy/proxy/layers/tls.py @@ -393,6 +393,11 @@ def on_handshake_error(self, err: str) -> layer.CommandGenerator[None]: err = f"The client may not trust the proxy's certificate for {dest} ({err})" yield commands.Log(f"Client TLS handshake failed. {err}", level="warn") yield from super().on_handshake_error(err) + self.event_to_child = self.errored # type: ignore + + def errored(self, event: events.Event) -> layer.CommandGenerator[None]: + if self.debug is not None: + yield commands.Log(f"Swallowing {event} as handshake failed.", "debug") class MockTLSLayer(_TLSLayer):
diff --git a/test/helper_tools/loggrep.py b/test/helper_tools/loggrep.py new file mode 100755 --- /dev/null +++ b/test/helper_tools/loggrep.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +import fileinput +import sys + +if __name__ == "__main__": + if len(sys.argv) < 3: + print(f"Usage: {sys.argv[0]} port filenames") + sys.exit() + + port = sys.argv[1] + matches = False + for line in fileinput.input(sys.argv[2:]): + if line.startswith("["): + matches = port in line + if matches: + print(line, end="") diff --git a/test/mitmproxy/proxy/layers/test_tls.py b/test/mitmproxy/proxy/layers/test_tls.py --- a/test/mitmproxy/proxy/layers/test_tls.py +++ b/test/mitmproxy/proxy/layers/test_tls.py @@ -476,6 +476,15 @@ def test_cannot_parse_clienthello(self, tctx: context.Context): ) assert not tctx.client.tls_established + # Make sure that an active server connection does not cause child layers to spawn. + client_layer.debug = "" + assert ( + playbook + >> events.DataReceived(Server(None), b"data on other stream") + << commands.Log(">> DataReceived(server, b'data on other stream')", 'debug') + << commands.Log("Swallowing DataReceived(server, b'data on other stream') as handshake failed.", "debug") + ) + def test_mitmproxy_ca_is_untrusted(self, tctx: context.Context): """Test the scenario where the client doesn't trust the mitmproxy CA.""" playbook, client_layer, tssl_client = make_client_tls_layer(tctx, sni=b"wrong.host.mitmproxy.org")
AssertionError: assert not self.tls The repro website is NSFW / porn (see also https://hackerone.com/chaturbate) #### Problem Description ``` [::1]:60890: mitmproxy has crashed! Traceback (most recent call last): File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 144, in handle_event command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 255, in handle_event yield from self._handle(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 144, in handle_event command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 613, in _handle_event yield from self.event_to_child(stream, event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 649, in event_to_child for command in child.handle_event(event): File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 144, in handle_event command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 531, in passthrough for command in self.child_layer.handle_event(event): File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 129, in handle_event yield from self.__continue(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 220, in __continue yield from self.__process(command_generator, event.reply) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 183, in __process command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 306, in event_to_child yield from super().event_to_child(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 124, in event_to_child yield from self.start_handshake() File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 294, in start_handshake yield from self.start_tls() File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 152, in start_tls assert not self.tls AssertionError ``` #### Steps to reproduce the behavior: 1. `mitmdump --quiet` 2. Visit `https://chaturbate.com` in Chromium ``` chromium --user-data-dir=`mktemp --directory` --start-maximized --no-default-browser-check --no-first-run --disable-translate --disable-extensions --incognito --proxy-server="localhost:8080" https://chaturbate.com ``` (don't mind all the arguments, I use that all the time aliased as `clean-chrome-instance`) #### System Information ``` Mitmproxy: 7.0.0.dev (+417, commit 1b0fce6) Python: 3.8.5 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-5.8.0-48-generic-x86_64-with-glibc2.29 ```
Happens on https://imgur.com/ as well I originally thought this was unrelated, but I'm seeing duplicate connection IDs with the crash (thank my UNIQUE contraints) ```py _serverConnectionIds = {} def server_connected(data): global _serverConnectionIds server = data.server if server.id in _serverConnectionIds: print('duplicate') print(server.id) else: _serverConnectionIds[server.id] = True ``` ``` duplicate 08c89ca2-3f4d-45ae-ab1b-4ca71be87ed8 [::1]:33644: mitmproxy has crashed! Traceback (most recent call last): File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/server.py", line 276, in server_event for command in layer_commands: File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 144, in handle_event command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 255, in handle_event yield from self._handle(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 144, in handle_event command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 613, in _handle_event yield from self.event_to_child(stream, event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 649, in event_to_child for command in child.handle_event(event): File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 144, in handle_event command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 531, in passthrough for command in self.child_layer.handle_event(event): File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 129, in handle_event yield from self.__continue(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 220, in __continue yield from self.__process(command_generator, event.reply) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layer.py", line 183, in __process command = command_generator.send(send) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 85, in _handle_event yield from self.event_to_child(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 306, in event_to_child yield from super().event_to_child(event) File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/tunnel.py", line 124, in event_to_child yield from self.start_handshake() File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 294, in start_handshake yield from self.start_tls() File "/home/alex/src/forks/mitmproxy/mitmproxy/proxy/layers/tls.py", line 152, in start_tls assert not self.tls AssertionError ``` My guess (as always) are race conditions. That's why I use these websites, they produce a lot of requests (tons of images at once). There is definitely no other reason to use them. Thanks! That's very likely caused by aa815a52469ce8e09f404c6f5e66af0f47c78829. We need a log with `--set proxy_debug -vvv`. If you have one great, otherwise I'll see if I can reproduce this in ~2 weeks. There are some AssertionError in there [vvv.log](https://github.com/mitmproxy/mitmproxy/files/6273115/vvv.log) Edit: it does not happen with connection_strategy=lazy
2021-05-11T13:44:18
mitmproxy/mitmproxy
4,618
mitmproxy__mitmproxy-4618
[ "4617" ]
27883e7b05032961cbee2b0f6a6867e4cc5d11d6
diff --git a/mitmproxy/http.py b/mitmproxy/http.py --- a/mitmproxy/http.py +++ b/mitmproxy/http.py @@ -86,7 +86,7 @@ class Headers(multidict.MultiDict): # type: ignore >>> h.fields Caveats: - - For use with the "Set-Cookie" header, either use `Response.cookies` or see `Headers.get_all`. + - For use with the "Set-Cookie" and "Cookie" headers, either use `Response.cookies` or see `Headers.get_all`. """ def __init__(self, fields: Iterable[Tuple[bytes, bytes]] = (), **headers): @@ -142,9 +142,12 @@ def __iter__(self) -> Iterator[str]: def get_all(self, name: Union[str, bytes]) -> List[str]: """ Like `Headers.get`, but does not fold multiple headers into a single one. - This is useful for Set-Cookie headers, which do not support folding. + This is useful for Set-Cookie and Cookie headers, which do not support folding. - *See also:* <https://tools.ietf.org/html/rfc7230#section-3.2.2> + *See also:* + - <https://tools.ietf.org/html/rfc7230#section-3.2.2> + - <https://datatracker.ietf.org/doc/html/rfc6265#section-5.4> + - <https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.5> """ name = _always_bytes(name) return [
Cannot access raw cookie header / incorrect folding #### Problem Description I just noticed that on my end the `cookie` header contains multiple comma separated cookies, which is not valid. The original request by Chromium had them all in a single header separated by semicolons. I assume mitmproxy splits the cookies into multiple headers and incorrectly puts them back together (by folding via comma) even though I explicitly want the rawest of raw headers via `h.fields`. How do I get the actual raw header key / values without any manipulation by mitmproxy? The docs only mention issues with `set-cookie` and amusingly the library I'm using does [actually support folding](https://github.com/nfriedly/set-cookie-parser/blob/2628d67bd0718c38bd1c028ee0fce6cda56e55be/test/split-cookies-string.js) but [not for `cookie`](https://github.com/jshttp/cookie/issues/62). For cookie we have https://datatracker.ietf.org/doc/html/rfc6265#section-5.4 > When the user agent generates an HTTP request, the user agent MUST NOT attach more than one Cookie header field. and https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.5 > The Cookie header field [COOKIE] uses a semi-colon (";") to delimit cookie-pairs (or "crumbs"). This header field doesn't follow the list construction rules in HTTP (see [RFC7230], Section 3.2.2), which prevents cookie-pairs from being separated into different name-value pairs. This can significantly reduce compression efficiency as individual cookie-pairs are updated. > To allow for better compression efficiency, the Cookie header field MAY be split into separate header fields, each with one or more cookie-pairs. If there are multiple Cookie header fields after decompression, these MUST be concatenated into a single octet string using the two-octet delimiter of 0x3B, 0x20 (the ASCII string "; ") before being passed into a non-HTTP/2 context, such as an HTTP/1.1 connection, or a generic HTTP server application. > Therefore, the following two lists of Cookie header fields are semantically equivalent. > cookie: a=b; c=d; e=f > cookie: a=b > cookie: c=d > cookie: e=f #### Steps to reproduce the behavior: I was using github.com in a private window: ```py def request(flow): if flow.request.url == 'https://github.com/': print('=======================') print(flow.request.headers) print('------------------') print(flow.request.headers.items()) print('------------------') print(flow.request.headers.fields) print('------------------') for name, value in flow.request.headers.items(): if name == 'cookie': print(name, value) print('------------------') print('=======================') ``` ```sh mitmdump --quiet --scripts cookie.py ``` ``` ======================= Headers[(b'cache-control', b'max-age=0'), (b'sec-ch-ua', b'"Chromium";v="91", " Not;A Brand";v="99"'), (b'sec-ch-ua-mobile', b'?0'), (b'upgrade-insecure-requests', b'1'), (b'user-agent', b'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'), (b'accept', b'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'), (b'sec-fetch-site', b'none'), (b'sec-fetch-mode', b'navigate'), (b'sec-fetch-user', b'?1'), (b'sec-fetch-dest', b'document'), (b'accept-encoding', b'gzip, deflate, br'), (b'accept-language', b'en-US,en;q=0.9'), (b'cookie', b'_octo=GH1.1.165320981.1622543172'), (b'cookie', b'logged_in=no'), (b'cookie', b'tz=Europe%2FBerlin'), (b'cookie', b'_gh_sess=*****'), (b'if-none-match', b'W/"e1519975261cdc6739507b7f0666ade0"')] ------------------ ItemsView(Headers[(b'cache-control', b'max-age=0'), (b'sec-ch-ua', b'"Chromium";v="91", " Not;A Brand";v="99"'), (b'sec-ch-ua-mobile', b'?0'), (b'upgrade-insecure-requests', b'1'), (b'user-agent', b'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'), (b'accept', b'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'), (b'sec-fetch-site', b'none'), (b'sec-fetch-mode', b'navigate'), (b'sec-fetch-user', b'?1'), (b'sec-fetch-dest', b'document'), (b'accept-encoding', b'gzip, deflate, br'), (b'accept-language', b'en-US,en;q=0.9'), (b'cookie', b'_octo=GH1.1.165320981.1622543172'), (b'cookie', b'logged_in=no'), (b'cookie', b'tz=Europe%2FBerlin'), (b'cookie', b'_gh_sess=*****'), (b'if-none-match', b'W/"e1519975261cdc6739507b7f0666ade0"')]) ------------------ ((b'cache-control', b'max-age=0'), (b'sec-ch-ua', b'"Chromium";v="91", " Not;A Brand";v="99"'), (b'sec-ch-ua-mobile', b'?0'), (b'upgrade-insecure-requests', b'1'), (b'user-agent', b'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'), (b'accept', b'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'), (b'sec-fetch-site', b'none'), (b'sec-fetch-mode', b'navigate'), (b'sec-fetch-user', b'?1'), (b'sec-fetch-dest', b'document'), (b'accept-encoding', b'gzip, deflate, br'), (b'accept-language', b'en-US,en;q=0.9'), (b'cookie', b'_octo=GH1.1.165320981.1622543172'), (b'cookie', b'logged_in=no'), (b'cookie', b'tz=Europe%2FBerlin'), (b'cookie', b'_gh_sess=*****'), (b'if-none-match', b'W/"e1519975261cdc6739507b7f0666ade0"')) ------------------ cookie _octo=GH1.1.165320981.1622543172, logged_in=no, tz=Europe%2FBerlin, _gh_sess=***** ------------------ ======================= ``` You can see that even `fields` has them split. And that iterating `items()` will incorrectly fold the header with commas. Chromium network tab (one header, multiple cookies with semicolon): ``` cookie: _octo=GH1.1.165320981.1622543172; logged_in=no; tz=Europe%2FBerlin; _gh_sess=***** ``` #### System Information ``` Mitmproxy: 7.0.0.dev (+451, commit 27883e7) Python: 3.8.5 OpenSSL: OpenSSL 1.1.1i 8 Dec 2020 Platform: Linux-5.8.0-53-generic-x86_64-with-glibc2.29 ```
I'm using `connection_strategy=lazy` on my end so this shouldn't be one of those HTTP/1.1 vs HTTP/2.0 transparent interop issues? It might just be that the dev tools are lying :thinking: Ok, so disabling HTTP2 in mitmproxy behaves as I was expecting it and the dev tools are in fact lying. With HTTP/2.0 I get multiple cookie headers from Chromium. So this is probably just a matter of documenting the issues with cookie similar to set-cookie? I have to sleep a night on that :sweat_smile: `Message.headers.fields` should always have the headers as received on-the-wire. Do https://docs.mitmproxy.org/dev/api/mitmproxy/http.html#Headers and https://docs.mitmproxy.org/dev/api/mitmproxy/http.html#Headers.get_all explain the rest? 😃
2021-06-02T08:18:27