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 | 4,631 | mitmproxy__mitmproxy-4631 | [
"4630",
"4630"
] | de0951462d5919c6d37bed5f8f3b80d8f810b833 | diff --git a/mitmproxy/addons/tlsconfig.py b/mitmproxy/addons/tlsconfig.py
--- a/mitmproxy/addons/tlsconfig.py
+++ b/mitmproxy/addons/tlsconfig.py
@@ -169,18 +169,19 @@ def create_proxy_server_ssl_conn(self, tls_start: tls.TlsStartData) -> None:
if not server.alpn_offers:
if client.alpn_offers:
if ctx.options.http2:
+ # We would perfectly support HTTP/1 -> HTTP/2, but we want to keep things on the same protocol
+ # version. There are some edge cases where we want to mirror the regular server's behavior
+ # accurately, for example header capitalization.
server.alpn_offers = tuple(client.alpn_offers)
else:
server.alpn_offers = tuple(x for x in client.alpn_offers if x != b"h2")
- elif client.tls_established:
- # We would perfectly support HTTP/1 -> HTTP/2, but we want to keep things on the same protocol version.
- # There are some edge cases where we want to mirror the regular server's behavior accurately,
- # for example header capitalization.
- server.alpn_offers = []
- elif ctx.options.http2:
- server.alpn_offers = tls.HTTP_ALPNS
else:
- server.alpn_offers = tls.HTTP1_ALPNS
+ # We either have no client TLS or a client without ALPN.
+ # - If the client does use TLS but did not send an ALPN extension, we want to mirror that upstream.
+ # - If the client does not use TLS, there's no clear-cut answer. As a pragmatic approach, we also do
+ # not send any ALPN extension in this case, which defaults to whatever protocol we are speaking
+ # or falls back to HTTP.
+ server.alpn_offers = []
if not server.cipher_list and ctx.options.ciphers_server:
server.cipher_list = ctx.options.ciphers_server.split(":")
| diff --git a/test/helper_tools/loggrep.py b/test/helper_tools/loggrep.py
--- a/test/helper_tools/loggrep.py
+++ b/test/helper_tools/loggrep.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
import fileinput
import sys
+import re
if __name__ == "__main__":
if len(sys.argv) < 3:
@@ -10,7 +11,7 @@
port = sys.argv[1]
matches = False
for line in fileinput.input(sys.argv[2:]):
- if line.startswith("["):
+ if re.match(r"^\[|(\d+\.){3}", line):
matches = port in line
if matches:
print(line, end="")
diff --git a/test/mitmproxy/addons/test_tlsconfig.py b/test/mitmproxy/addons/test_tlsconfig.py
--- a/test/mitmproxy/addons/test_tlsconfig.py
+++ b/test/mitmproxy/addons/test_tlsconfig.py
@@ -190,8 +190,8 @@ def assert_alpn(http2, client_offers, expected):
assert_alpn(True, tls.HTTP_ALPNS + (b"foo",), tls.HTTP_ALPNS + (b"foo",))
assert_alpn(False, tls.HTTP_ALPNS + (b"foo",), tls.HTTP1_ALPNS + (b"foo",))
- assert_alpn(True, [], tls.HTTP_ALPNS)
- assert_alpn(False, [], tls.HTTP1_ALPNS)
+ assert_alpn(True, [], [])
+ assert_alpn(False, [], [])
ctx.client.timestamp_tls_setup = time.time()
# make sure that we don't upgrade h1 to h2,
# see comment in tlsconfig.py
| Instagram TCP connections broken with HTTP2 enabled
#### Problem Description
Using the latest binary (v7) with HTTP2 enabled and in SOCKS mode, Instagram on Android can't use MQTT through TCP anymore.
Other Facebook apps might also be affected as they use a similar connection.
In an affected version, you can see a lot of TCP connections to two different hosts with the same port (443). If you look at the tcp messages, the last message is always `missing connection preface` (then the connection is closed).
This doesn't happen if mitmproxy has HTTP2 disabled (instagram uses http2, so you only see tcp connections but the MQTT connections mentioned at the start work fine; there are two persistent connections).
I beleive this was introduced in #4529 (commit `f94a9a3`) as the build for #4532 (commit `0e8dd73`) doesn't have this issue.
#### Steps to reproduce the behavior:
0. Have an Instagram account with [WhiteHat mode](https://www.facebook.com/whitehat) enabled (and enable no TLS 1.3 and allow user certificates in the app).
1. Fully close Instagram
2. Start mitmproxy in SOCKS mode
3. Open Instagram
#### System Information
```
Mitmproxy: 7.0.0.dev binary
Python: 3.9.2
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Windows-10-10.0.19041-SP0
```
Instagram TCP connections broken with HTTP2 enabled
#### Problem Description
Using the latest binary (v7) with HTTP2 enabled and in SOCKS mode, Instagram on Android can't use MQTT through TCP anymore.
Other Facebook apps might also be affected as they use a similar connection.
In an affected version, you can see a lot of TCP connections to two different hosts with the same port (443). If you look at the tcp messages, the last message is always `missing connection preface` (then the connection is closed).
This doesn't happen if mitmproxy has HTTP2 disabled (instagram uses http2, so you only see tcp connections but the MQTT connections mentioned at the start work fine; there are two persistent connections).
I beleive this was introduced in #4529 (commit `f94a9a3`) as the build for #4532 (commit `0e8dd73`) doesn't have this issue.
#### Steps to reproduce the behavior:
0. Have an Instagram account with [WhiteHat mode](https://www.facebook.com/whitehat) enabled (and enable no TLS 1.3 and allow user certificates in the app).
1. Fully close Instagram
2. Start mitmproxy in SOCKS mode
3. Open Instagram
#### System Information
```
Mitmproxy: 7.0.0.dev binary
Python: 3.9.2
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Windows-10-10.0.19041-SP0
```
| Thanks! A few questions:
- Can you reproduce this with `--set connection_strategy=lazy`?
- Which version are you on exactly? Downloaded today/in the last few days?
Also, a `mitmdump --set proxy_debug -vvv` log would be fabulous. If you are unsure whether it contains private data feel free to shoot me an email. :)
> Can you reproduce this with `--set connection_strategy=lazy`?
I can't. With this option (?) set, it works fine.
> Which version are you on exactly? Downloaded today/in the last few days?
The mitmdump logs I'll send you are on the latest build. The first occurence of this issue was after #4529 landed, so basically [this build](https://github.com/mitmproxy/mitmproxy/commit/f94a9a3c9dc6cc1ebfda7038676aa64560bd4f56). The previous build was fine.
I sent you the log via email.
Repro:
```
mitmdump -vvv --set proxy_debug --mode socks5
curl -x socks5h://localhost:8080 -k https://facebook.com -v --no-alpn
```
I'll have a fix out momentarily. 😃
Thanks! A few questions:
- Can you reproduce this with `--set connection_strategy=lazy`?
- Which version are you on exactly? Downloaded today/in the last few days?
Also, a `mitmdump --set proxy_debug -vvv` log would be fabulous. If you are unsure whether it contains private data feel free to shoot me an email. :)
> Can you reproduce this with `--set connection_strategy=lazy`?
I can't. With this option (?) set, it works fine.
> Which version are you on exactly? Downloaded today/in the last few days?
The mitmdump logs I'll send you are on the latest build. The first occurence of this issue was after #4529 landed, so basically [this build](https://github.com/mitmproxy/mitmproxy/commit/f94a9a3c9dc6cc1ebfda7038676aa64560bd4f56). The previous build was fine.
I sent you the log via email.
Repro:
```
mitmdump -vvv --set proxy_debug --mode socks5
curl -x socks5h://localhost:8080 -k https://facebook.com -v --no-alpn
```
I'll have a fix out momentarily. 😃 | 2021-06-09T22:10:18 |
mitmproxy/mitmproxy | 4,643 | mitmproxy__mitmproxy-4643 | [
"4642",
"4642"
] | 34a620e57b0db3621d064c6ff83440c1023f1c9d | diff --git a/mitmproxy/addons/next_layer.py b/mitmproxy/addons/next_layer.py
--- a/mitmproxy/addons/next_layer.py
+++ b/mitmproxy/addons/next_layer.py
@@ -115,9 +115,13 @@ def s(*layers):
# 2. Check for TLS
if client_tls:
# client tls usually requires a server tls layer as parent layer, except:
- # - reverse proxy mode manages this itself.
# - a secure web proxy doesn't have a server part.
- if s(modes.ReverseProxy) or s(modes.HttpProxy):
+ # - reverse proxy mode manages this itself.
+ if (
+ s(modes.HttpProxy) or
+ s(modes.ReverseProxy) or
+ s(modes.ReverseProxy, layers.ServerTLSLayer)
+ ):
return layers.ClientTLSLayer(context)
else:
# We already assign the next layer here os that ServerTLSLayer
@@ -127,11 +131,11 @@ def s(*layers):
return ret
# 3. Setup the HTTP layer for a regular HTTP proxy or an upstream proxy.
- if any([
- s(modes.HttpProxy),
+ if (
+ s(modes.HttpProxy) or
# or a "Secure Web Proxy", see https://www.chromium.org/developers/design-documents/secure-web-proxy
- s(modes.HttpProxy, layers.ClientTLSLayer),
- ]):
+ s(modes.HttpProxy, layers.ClientTLSLayer)
+ ):
if ctx.options.mode == "regular":
return layers.HttpLayer(context, HTTPMode.regular)
else:
| v7 reverse proxying tcp protocols crashing
#### Problem Description
i'm trying to proxy tcp protocols and periodically getting a crash:
./mitmdump --set termlog_verbosity=debug --mode reverse:https://pop.gmail.com:995 --set connection_strategy=eager -w mail --set flow_detail=3 -p 8181
```console
% ./mitmdump --set termlog_verbosity=debug --mode reverse:https://pop.gmail.com:995 --set connection_strategy=eager -w mail --set flow_detail=3 -p 8181
Proxy server listening at http://*:8181
[::1]:64076: client connect
[::1]:64076: server connect pop.gmail.com (172.253.123.109:995)
[::1]:64076: mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 279, in server_event
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 240, in receive_data
File "mitmproxy/proxy/layers/tls.py", line 306, in event_to_child
File "mitmproxy/proxy/tunnel.py", line 104, in event_to_child
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 225, in receive_data
AttributeError: 'NoneType' object has no attribute 'bio_write'
[::1]:64076: client disconnect
[::1]:64076: closing transports...
[::1]:64076: server disconnect pop.gmail.com (172.253.123.109:995)
[::1]:64076: transports closed!
[::1]:64180: client connect
[::1]:64180: server connect pop.gmail.com (172.253.123.109:995)
[::1]:64180 <- tcp <- pop.gmail.com:995
+OK Gpop ready for requests from 24.137.254.57 s4mb63968478vsi
[::1]:64180 -> tcp -> pop.gmail.com:995
CAPA
[::1]:64180 <- tcp <- pop.gmail.com:995
+OK Capability list follows
USER
RESP-CODES
EXPIRE 0
LOGIN-DELAY 300
TOP
UIDL
X-GOOGLE-RICO
SASL PLAIN XOAUTH2 OAUTHBEARER
.
[::1]:64180: half-closing Server(pop.gmail.com:995, state=open, tls, src_port=64181)
[::1]:64180: server disconnect pop.gmail.com (172.253.123.109:995)
[::1]:64180: client disconnect
[::1]:64180: closing transports...
[::1]:64180: transports closed!
```
#### System Information
% ./mitmdump --version
Mitmproxy: 7.0.0.dev binary
Python: 3.9.5
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: macOS-11.2.3-x86_64-i386-64bit
v7 reverse proxying tcp protocols crashing
#### Problem Description
i'm trying to proxy tcp protocols and periodically getting a crash:
./mitmdump --set termlog_verbosity=debug --mode reverse:https://pop.gmail.com:995 --set connection_strategy=eager -w mail --set flow_detail=3 -p 8181
```console
% ./mitmdump --set termlog_verbosity=debug --mode reverse:https://pop.gmail.com:995 --set connection_strategy=eager -w mail --set flow_detail=3 -p 8181
Proxy server listening at http://*:8181
[::1]:64076: client connect
[::1]:64076: server connect pop.gmail.com (172.253.123.109:995)
[::1]:64076: mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 279, in server_event
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 240, in receive_data
File "mitmproxy/proxy/layers/tls.py", line 306, in event_to_child
File "mitmproxy/proxy/tunnel.py", line 104, in event_to_child
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 225, in receive_data
AttributeError: 'NoneType' object has no attribute 'bio_write'
[::1]:64076: client disconnect
[::1]:64076: closing transports...
[::1]:64076: server disconnect pop.gmail.com (172.253.123.109:995)
[::1]:64076: transports closed!
[::1]:64180: client connect
[::1]:64180: server connect pop.gmail.com (172.253.123.109:995)
[::1]:64180 <- tcp <- pop.gmail.com:995
+OK Gpop ready for requests from 24.137.254.57 s4mb63968478vsi
[::1]:64180 -> tcp -> pop.gmail.com:995
CAPA
[::1]:64180 <- tcp <- pop.gmail.com:995
+OK Capability list follows
USER
RESP-CODES
EXPIRE 0
LOGIN-DELAY 300
TOP
UIDL
X-GOOGLE-RICO
SASL PLAIN XOAUTH2 OAUTHBEARER
.
[::1]:64180: half-closing Server(pop.gmail.com:995, state=open, tls, src_port=64181)
[::1]:64180: server disconnect pop.gmail.com (172.253.123.109:995)
[::1]:64180: client disconnect
[::1]:64180: closing transports...
[::1]:64180: transports closed!
```
#### System Information
% ./mitmdump --version
Mitmproxy: 7.0.0.dev binary
Python: 3.9.5
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: macOS-11.2.3-x86_64-i386-64bit
| Thanks for testing the 7.0 snapshots! Any idea how I can reproduce this? Can you trigger this with `-vvv -set proxy_debug`? An extended log would be incredibly helpful for debugging this. Feel free to shoot me an email with your logs if you want to keep them private.
to reproduce this (if you have a mac), i'm using the Apple Mail.app. Set up a POP / SMTP account and point the POP one at localhost 8181, TLS on, password auth.
```console
./mitmdump --set termlog_verbosity=debug --mode reverse:https://pop.gmail.com:995 --set connection_strategy=eager -w mail_debug --set flow_detail=3 -p 8181 -vvv --set proxy_debug=true
Proxy server listening at http://*:8181
[::1]:65101: client connect
[::1]:65101: >> Start({})
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: >! DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:65101: [nextlayer] ReverseProxy()
[::1]:65101: >> Start({})
[::1]:65101: << OpenConnection({'connection': Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'pop.gmail.com', 'tls': True})})
[::1]:65101: << OpenConnection({'connection': Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'pop.gmail.com', 'tls': True})})
[::1]:65101: !> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >! DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: server connect pop.gmail.com (172.217.193.108:995)
[::1]:65101: >> Reply(OpenConnection({'connection': Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'peername': ('172.217.193.108', 995), 'sockname': ('192.168.86.222', 65102)})}),None)
[::1]:65101: >> Start({})
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'peername': ('172.217.193.108', 995), 'sockname': ('192.168.86.222', 65102)}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=None))
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'pee…
[::1]:65101: !> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >! DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'peername': ('172.217.193.108', 995), 'sockname': ('192.168.86.222', 65102), 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=<OpenSSL.SSL.Connection object at 0x112e7ea30>)),None)
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208…
[::1]:65101: << SendData(server, b"\x16\x03\x01\x01.\x01\x00\x01*\x03\x03\xf5z4\x7fG\x08)(\x08SZ\xba\x9b\x9e\x9dD\xf0Ixw\xe7\x0e\x0e\x0b\x0e\x92,\xaeG[\x94\xcd p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x00:\x13\x02\x13\x03\x13\x01\xc0+\xc0/\xc0,\xc00\xcc\xa9\xcc\xa8\x00\x9e\x00\x9f\xcc\xaa\xc0#\xc0'\xc0\t\xc0\x13\xc0$\xc0(\xc0\n\xc0\x14\x00g\x00k\x00\x9c\x00\x9d\x00<\x00=\x00/\x005\x00\xff\x01\x00\x00\xa7\x00\x00\x00\x12\x00\x10\x00\x00\rpop.gmail.com\x00\x0b\x00\x04\x0…
[::1]:65101: << SendData(server, b"\x16\x03\x01\x01.\x01\x00\x01*\x03\x03\xf5z4\x7fG\x08)(\x08SZ\xba\x9b\x9e\x9dD\xf0Ixw\xe7\x0e\x0e\x0b\x0e\x92,\xaeG[\x94\xcd p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x00:\x13\x02\x13…
[::1]:65101: !> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\x97jY\x87\xf0\xe4C\x8c?\xd1\x98>\x0b\x16\x11\xf9\xcfz\xe5R\x85\x83p\xd1\xa7e\xeb\x81N,8I p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x13\x02\x00\x00.\x003\x00$\x00\x1d\x00 \xd1,\xfc\xcaeS\x9c`0tQ\xa8\x8d\xbd2\xb0b\xae\x8a\xae\xac\x8cAS\xe7\x153\xebl2\x8cB\x00+\x00\x02\x03\x04\x14\x03\x03\x00\x01\x01\x17\x03\x03\t\xc5\x0e\xcfDu\n\xca\xccv%\xe2\xc5\xd3!\xad\x9a\xe6\xf9\x90\xda6\x06,5\xeb a\xe6~\xd…
[::1]:65101: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\x97jY\x87\xf0\xe4C\x8c?\xd1\x98>\x0b\x16\x11\xf9\xcfz\xe5R\x85\x83p\xd1\xa7e\xeb\x81N,8I p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x13\x02\x…
[::1]:65101: [tls] tls established: Server(pop.gmail.com:995, state=open, tls, src_port=65102)
[::1]:65101: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00Er\xef\xed\xcd=\x8f7\x8b\nl\xb2Sn\xdc\xc7*i\x05\xa5\xb7\x02%Ur}\xade\x05\xa1\x0e\x8ed\xa5\xec\x9d\x8b\x1a9&O\xac)*\xbe\xf1]\xce\x1a{\xf8\x95\xf9\x89\xc6\xe4\x14\x94\xacy/\xc8D\xa8\xb3e\x1do\x85\xaa')
[::1]:65101: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00Er\xef\xed\xcd=\x8f7\x8b\nl\xb2Sn\xdc\xc7*i\x05\xa5\xb7\x02%Ur}\xade\x05\xa1\x0e\x8ed\xa5\xec\x9d\x8b\x1a9&O\xac)*\xbe\xf1]\xce\x1a{\xf8\x95\xf9\x89\xc6\xe4\x14\x94\xacy/\xc8D\xa8\xb3e\x1do\x85\…
[::1]:65101: >> Start({})
[::1]:65101: >> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive pop.gmail.com b'')),None)
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive pop.gmail.com b'')),None)
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive pop.gmail.com b'')),None)
[::1]:65101: [nextlayer] ServerTLSLayer(inactive pop.gmail.com b'')
[::1]:65101: >> Start({})
[::1]:65101: >> Start({})
[::1]:65101: >> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0…
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=None))
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'al…
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'al…
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'al…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=<OpenSSL.SSL.Connection object at 0x112ea0550>)),None)
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01\x00\x01\x00\x00\x0b\x00\x04\x03\x00\x01\x02\x00\x17\x00\x00\x16\x03\x03\x03-\x0b\x00\x03)\x00\x03&\x00\x03#0\x82\x03\x1f0\x82\x02\x07\xa0\x03\x02\x01\x02\x02\x14?k\xa4\x82\x87\xc9aA\x14\x80\xf7\x99Nd\x00\xa5DL}.0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x0…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xc3\xb1\x19\x14\x01v\xeb\xa3^\x14+\xcc\xd7\x9b\xeb:\xe3\xe0<\x1f\xd3p\xb8I&\xc4\x01\xd8\xd0&3\xa9x}\xc7\xefye\xf8\xc2')
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x…
[::1]:65101: [tls] tls established: Client([::1]:65101, state=open, tls)
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: >> Start({})
[::1]:65101: >> DataReceived(server, b"\x17\x03\x03\x02\x15\x1f\x0f\xb7\xef\x12\xe1\x122~\xf0\x98\xe3\x1c2\x99\x88\x84\x96\xe2]n\x9c\xf6P\x12C\x825\x83\x1c>_\xa6\xa9\x90\x8f\x92\xc8Q\x1e#\xef\xe5.\xfa\xf6L\x7f\xc7Q\x83d\xe2\x01\xab)\xa1\xbd\xd8\xb2\xe7\xfa\xdcM\xfe\xde'\xb9\xe5\x07\n\xdcR_\xbb\xc2\x81\x84k/\xe3\xd0N\xcc\x98\x03\xc7\xa4g\xa6\xe8_A$\xd8\xbf[\x95\xe1s\xea\xc6\xbb\xbe\xdb\x7f\x8d\x04[\xe8\xe30\x8a\xc6\x84\x1c\x0b\x88\x95\xcc\x13u$s\x1a\x01\xeb\xcf\xf9\r/\xdf\x19\xa8a\x17w\xc5\xdf\xe7!\\c\x1c\xc9\x9a\xb2\x0e…
[::1]:65101: >> DataReceived(server, b"\x17\x03\x03\x02\x15\x1f\x0f\xb7\xef\x12\xe1\x122~\xf0\x98\xe3\x1c2\x99\x88\x84\x96\xe2]n\x9c\xf6P\x12C\x825\x83\x1c>_\xa6\xa9\x90\x8f\x92\xc8Q\x1e#\xef\xe5.\xfa\xf6L\x7f\xc7Q\x83d\xe2\x01\xab)\xa1\xbd\xd8\xb2\xe7\xfa\xdcM\xfe\xde…
[::1]:65101: >> DataReceived(server, b'+OK Gpop ready for requests from 24.137.254.57 p23mb49974932uao\r\n')
[::1]:65101: mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 279, in server_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 240, in receive_data
File "mitmproxy/proxy/layers/tls.py", line 306, in event_to_child
File "mitmproxy/proxy/tunnel.py", line 104, in event_to_child
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 225, in receive_data
AttributeError: 'NoneType' object has no attribute 'bio_write'
```
Thanks, this is super helpful! I'll take a look later today.
also crashing on SMTP. from the mail client:
```console
INITIATING CONNECTION Jun 17 12:49:46.234 host:localhost -- port:8282 -- socket:0x0 -- thread:0x600003691340
CONNECTED Jun 17 12:49:46.479 [kCFStreamSocketSecurityLevelTLSv1_2] -- host:localhost -- port:8282 -- socket:0x600000ac0180 -- thread:0x600003691340
```
mitmdump:
```console
% ./mitmdump --mode reverse:https://smtp.gmail.com:465 --set connection_strategy=eager -p8282 -vvv --set proxy_debug=true
Proxy server listening at http://*:8282
[::1]:50064: client connect
[::1]:50064: >> Start({})
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:50064: [nextlayer] ReverseProxy()
[::1]:50064: >> Start({})
[::1]:50064: << OpenConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50064: << OpenConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50064: server connect smtp.gmail.com (172.217.204.109:465)
[::1]:50064: >> Reply(OpenConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065)})}),None)
[::1]:50064: >> Start({})
[::1]:50064: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065)}), context=<mitmproxy.proxy.context.Context object at 0x10f8cb850>, ssl_conn=None))
[::1]:50064: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, '…
[::1]:50064: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065), 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8cb850>, ssl_conn=<OpenSSL.SSL.Connection object at 0x10f8f4490>)),None)
[::1]:50064: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521…
[::1]:50064: << SendData(server, b"\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\x19\xe5\xff\x80d*\x14\x06\x1e\xf1\r\xe3\xb7\xf6\x7f\xe5G\xceH\x82bre\xc9\xf1B\x82#\xa5\x00\xfb\x89 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe4\xda\xd4\xdd\x00:\x13\x02\x13\x03\x13\x01\xc0+\xc0/\xc0,\xc00\xcc\xa9\xcc\xa8\x00\x9e\x00\x9f\xcc\xaa\xc0#\xc0'\xc0\t\xc0\x13\xc0$\xc0(\xc0\n\xc0\x14\x00g\x00k\x00\x9c\x00\x9d\x00<\x00=\x00/\x005\x00\xff\x01\x00\x00\xa8\x00\x00\x00\x13\x00\x11\x00\x00\x0esmtp.gmail…
[::1]:50064: << SendData(server, b"\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\x19\xe5\xff\x80d*\x14\x06\x1e\xf1\r\xe3\xb7\xf6\x7f\xe5G\xceH\x82bre\xc9\xf1B\x82#\xa5\x00\xfb\x89 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe4\xda\xd4\…
[::1]:50064: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\xa6\xc4\x8b,\n\x16\xc0\xba\xa7\xd3v\xc1\x89k\xe7\xc6\xfb\xb5\xcb\x9b3\xabac\x95\x00\xde\xa1\x1bm\xa5\x94 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe4\xda\xd4\xdd\x13\x02\x00\x00.\x003\x00$\x00\x1d\x00 \x94Ry\x13\xeb\xe4\xf3\r\x81\xb6\x90\xff\xe8\x12X\x16\x12\xab)\x93|}\xb5\xf0U\x1f\xa20I\xd3\xbd\x19\x00+\x00\x02\x03\x04\x14\x03\x03\x00\x01\x01\x17\x03\x03\t\xc7\xda\xb3\x8f\xe4N#\x10m\xb2\xaf\xb3\xecN\…
[::1]:50064: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\xa6\xc4\x8b,\n\x16\xc0\xba\xa7\xd3v\xc1\x89k\xe7\xc6\xfb\xb5\xcb\x9b3\xabac\x95\x00\xde\xa1\x1bm\xa5\x94 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe…
[::1]:50064: [tls] tls established: Server(smtp.gmail.com:465, state=open, tls, src_port=50065)
[::1]:50064: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\x15\xc2j\xf0\x90Q\x1d\xed\x83\x98\x84\xae\x16\xbc\x7f\xee\xedk\xf7\x8d)2^}\rM\x95\xda\x19\xc2\nX\xd0a\x04\xcc\xbbK\xff\xda\xbct\x1a&}:m\xedc\x0b\n\xda*\x88\x19\xe6\xa8\xf9\x82\xf3\xe4\xd7\xd3\xf3Q"\xd5\x1e\xba')
[::1]:50064: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\x15\xc2j\xf0\x90Q\x1d\xed\x83\x98\x84\xae\x16\xbc\x7f\xee\xedk\xf7\x8d)2^}\rM\x95\xda\x19\xc2\nX\xd0a\x04\xcc\xbbK\xff\xda\xbct\x1a&}:m\xedc\x0b\n\xda*\x88\x19\xe6\xa8\xf9\x82\xf3\xe4\xd7\xd3\…
[::1]:50064: >> Start({})
[::1]:50064: >> DataReceived(server, b'\x17\x03\x03\x02\x15cc]\x846\xa1\x15\xd4lZC"hr\xd6\xfb"\xa6\x14S\xa752V}F@\x8d\x8eg\xde\xaf\x15M\xf4r\x86F\x0em\rE[}w\x94^?f/\x88\x89\xce,\xbf!\n\xd8\x87\r\xe0\x01\xa4T][B\xa0\x7fu\x7f\xbb-\x1e\xfaU\x1f\xa7\x99\xa8o$\x899\x15k\x9a\xf1_Q\xb3\x17\x00\xcbr\xd7\x8f\xeb\xedb.<\xc5\x1c\xd4\x81\xd2G\xf8.\x00U$\xf4\xf0\xaa\x8b\xdf~Nd\x04\xdaL\xd5\xb3-\xcetJ\xa35B\x10^\xe0\x12!\xff$vy\xeb\xab8\t\x04d\x92B\xb2\xbe,\xc7*\x86\xe9+N*\x85_\xde\x91Z\n\xf8}\x95Wl\xcc\x91\xc2\xc9\xa3J59\xe7}e\xae\x…
[::1]:50064: >> DataReceived(server, b'\x17\x03\x03\x02\x15cc]\x846\xa1\x15\xd4lZC"hr\xd6\xfb"\xa6\x14S\xa752V}F@\x8d\x8eg\xde\xaf\x15M\xf4r\x86F\x0em\rE[}w\x94^?f/\x88\x89\xce,\xbf!\n\xd8\x87\r\xe0\x01\xa4T][B\xa0\x7fu\x7f\xbb-\x1e\xfaU\x1f\xa7\x99\xa8o$\x899\x15k\x9a…
[::1]:50064: >> DataReceived(server, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:50064: [nextlayer] TCPLayer(state: start)
[::1]:50064: >> Start({})
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: >! DataReceived(server, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:50064: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:50064: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:50064: !> DataReceived(server, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:50064 <- tcp <- smtp.gmail.com:465
[::1]:50064: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: << SendData(client, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << SendData(client, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << SendData(client, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: >> ConnectionClosed(connection=Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}))
[::1]:50064: >> ConnectionClosed(connection=Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}))
[::1]:50064: >> ConnectionClosed(connection=Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}))
[::1]:50064: << CloseConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065), 'alpn_offers': [], 'timestamp_tls_setup': 1623948574.6460001, 'alpn': b'', 'certificate_list': [<mitmproxy.certs.Cert object at 0x10f8f45b0>, <mitmproxy.certs.Cert object at 0x10f8f4640…
[::1]:50064: << CloseConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peern…
[::1]:50064: << CloseConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peern…
[::1]:50064: half-closing Server(smtp.gmail.com:465, state=open, tls, src_port=50065)
[::1]:50064: >> ConnectionClosed(connection=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065), 'alpn_offers': [], 'timestamp_tls_setup': 1623948574.6460001, 'alpn': b'', 'certificate_list': [<mitmproxy.certs.Cert object at 0x10f8f45b0>, <mitmproxy.certs.Cert object at 0x10f8f4640>…
[::1]:50064: >> ConnectionClosed(connection=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peerna…
[::1]:50064: >> ConnectionClosed(connection=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peerna…
[::1]:50064: << CloseConnection({'connection': Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}), 'half_close': False})
[::1]:50064: << CloseConnection({'connection': Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}), 'half_close': False})
[::1]:50064: << CloseConnection({'connection': Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}), 'half_close': False})
[::1]:50064: << TcpEndHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpEndHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpEndHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: server disconnect smtp.gmail.com (172.217.204.109:465)
[::1]:50064: client disconnect
[::1]:50064: >> Reply(TcpEndHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpEndHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpEndHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: closing transports...
[::1]:50064: transports closed!
[::1]:50104: client connect
[::1]:50104: >> Start({})
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: >! DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:50104: [nextlayer] ReverseProxy()
[::1]:50104: >> Start({})
[::1]:50104: << OpenConnection({'connection': Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50104: << OpenConnection({'connection': Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50104: !> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >! DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: server connect smtp.gmail.com (172.217.204.109:465)
[::1]:50104: >> Reply(OpenConnection({'connection': Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50105)})}),None)
[::1]:50104: >> Start({})
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50105)}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=None))
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'p…
[::1]:50104: !> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >! DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50105), 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=<OpenSSL.SSL.Connection object at 0x10f9173d0>)),None)
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.3362…
[::1]:50104: << SendData(server, b'\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\xcf\xd6\xdc\xb2\xd2\x17\xc1R\xdf\x1c\xb7\x1c\xa3\xd7f\xef\xb7R\x02a-\xfb\xb6c\xa2\xecn\x81\xba\xf9\x88\xc6 -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\xa1#q\x00:\x13\x02\x13\x03\x13\x01\xc0+\xc0/\xc0,\xc00\xcc\xa9\xcc\xa8\x00\x9e\x00\x9f\xcc\xaa\xc0#\xc0\'\xc0\t\xc0\x13\xc0$\xc0(\xc0\n\xc0\x14\x00g\x00k\x00\x9c\x00\x9d\x00<\x00=\x00/\x005\x00\xff\x01\x00\x00\xa8\x00\x00\x00\x13\x00\x11\x00\x00\x0esmtp.gma…
[::1]:50104: << SendData(server, b'\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\xcf\xd6\xdc\xb2\xd2\x17\xc1R\xdf\x1c\xb7\x1c\xa3\xd7f\xef\xb7R\x02a-\xfb\xb6c\xa2\xecn\x81\xba\xf9\x88\xc6 -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\x…
[::1]:50104: !> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\\\x93\x98\x8eM\x06\x98\x90I\xe8Z`\xb1\xf0V\x10\xd9"\x9aME\n\xfe\xa0\xb6\xb6\xa9\xc6\xe8\xce\xa0e -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\xa1#q\x13\x02\x00\x00.\x003\x00$\x00\x1d\x00 K\x03\xcd6\x88g\xf7\x90\xd8\xc4\x9f\x11\xf8\xd9[_egOb\x881)\x80\\\xc6}0L\x83\x01\x15\x00+\x00\x02\x03\x04\x14\x03\x03\x00\x01\x01\x17\x03\x03\t\xc5\xb2\x92\x97\x83\xf6bS\xd3\x95C\x17\xe5\x1d%\xd2\xc2W\x16\xa6\x05\xdd\x…
[::1]:50104: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\\\x93\x98\x8eM\x06\x98\x90I\xe8Z`\xb1\xf0V\x10\xd9"\x9aME\n\xfe\xa0\xb6\xb6\xa9\xc6\xe8\xce\xa0e -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\xa1#q\x…
[::1]:50104: [tls] tls established: Server(smtp.gmail.com:465, state=open, tls, src_port=50105)
[::1]:50104: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\xa8\xfa\xaeH\xa8J\x85\xb6w4S\xc1\xa3\xebT"\x00*i\xab\x04a\xc4\x04,\xcc\xfb\xbb\xc5d\xe1\xc3\x81{\\\xd0<\x16s\xf7\xb2!\xb93\n=\x85!\xb1\x9d\xc0\xb6\xfb\xf3\xcd7\xa9\xb8\xde^{.\xd2\xf0\xaa\xeb\x15\x98\xe2')
[::1]:50104: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\xa8\xfa\xaeH\xa8J\x85\xb6w4S\xc1\xa3\xebT"\x00*i\xab\x04a\xc4\x04,\xcc\xfb\xbb\xc5d\xe1\xc3\x81{\\\xd0<\x16s\xf7\xb2!\xb93\n=\x85!\xb1\x9d\xc0\xb6\xfb\xf3\xcd7\xa9\xb8\xde^{.\xd2\xf0\xaa\xeb\x…
[::1]:50104: >> Start({})
[::1]:50104: >> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive smtp.gmail.com b'')),None)
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive smtp.gmail.com b'')),None)
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive smtp.gmail.com b'')),None)
[::1]:50104: [nextlayer] ServerTLSLayer(inactive smtp.gmail.com b'')
[::1]:50104: >> Start({})
[::1]:50104: >> Start({})
[::1]:50104: >> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1…
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=None))
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'a…
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'a…
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'a…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=<OpenSSL.SSL.Connection object at 0x10f928e80>)),None)
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhos…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhos…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhos…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00\x11\xff\x01\x00\x01\x00\x00\x0b\x00\x04\x03\x00\x01\x02\x00\x17\x00\x00\x16\x03\x03\x03/\x0b\x00\x03+\x00\x03(\x00\x03%0\x82\x03!0\x82\x02\t\xa0\x03\x02\x01\x02\x02\x14\x1b\xbcbs\x95tRF_\x88d\xee\xb4fZ\xaf\x8e}\xfa/0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x0…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00…
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(L\x11|E\xa4\xc2\x84\xb0\xd4c\xa7"F\x11*\\\x11~\xa8o\xf0"\x9e\x80^-e\x86\xf8\x10\xa2\xe2_\xf8\x0f%\xd2\x08&\xcf')
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00…
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00…
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00…
[::1]:50104: [tls] tls established: Client([::1]:50104, state=open, tls)
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: >> Start({})
[::1]:50104: >> DataReceived(server, b'\x17\x03\x03\x02\x15\xb5\xb7\xb2\xd5\x0e\x8f\xd3\x0f\x87\xd2\\.\xbe\x03V\xb1\x9d_\x08\x8de$\xee\xb7\\L*\'Q\xe9\r\xb2\x04\x05\x04\xc05\xa1V;\x859\xdbq\xa2\xbd\xe8%\xef\x1a\xe7ii\x94kp\xfb\xed\xee\x93\xa8_\x9eR\x1d\n\xd1D\xe4\x91\xc8\xf4\x16\xf8\xf9\xfb[:\x82r"[\xa4\x89\x10[w6\x99\xe5\xa5\xe9\x0c\xf6\xc9n\x17\xc3\xd7v\x06\xd4\xc9\x06\xb7R>%\x81\x03\x9f5qI\t\x8b\xa14\x9e\x8e+\xdb\x1d\x9f<\xa0\x19+%\xd5;\xc2\xd3\xa0\x8c7\xa5\xfcWY0\xc9A\xeap\xa7kd\'-\xb3H\x9d\xbc\xe4$!C\xc4B\xadG\x89g\…
[::1]:50104: >> DataReceived(server, b'\x17\x03\x03\x02\x15\xb5\xb7\xb2\xd5\x0e\x8f\xd3\x0f\x87\xd2\\.\xbe\x03V\xb1\x9d_\x08\x8de$\xee\xb7\\L*\'Q\xe9\r\xb2\x04\x05\x04\xc05\xa1V;\x859\xdbq\xa2\xbd\xe8%\xef\x1a\xe7ii\x94kp\xfb\xed\xee\x93\xa8_\x9eR\x1d\n\xd1D\xe4\x91\xc…
[::1]:50104: >> DataReceived(server, b'220 smtp.gmail.com ESMTP e19sm712405uaa.16 - gsmtp\r\n')
[::1]:50104: mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 279, in server_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 240, in receive_data
File "mitmproxy/proxy/layers/tls.py", line 306, in event_to_child
File "mitmproxy/proxy/tunnel.py", line 104, in event_to_child
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 225, in receive_data
AttributeError: 'NoneType' object has no attribute 'bio_write'
```
Fantastic, thanks! I can reproduce it now, which generally makes fixing much easier. :)
Thanks for testing the 7.0 snapshots! Any idea how I can reproduce this? Can you trigger this with `-vvv -set proxy_debug`? An extended log would be incredibly helpful for debugging this. Feel free to shoot me an email with your logs if you want to keep them private.
to reproduce this (if you have a mac), i'm using the Apple Mail.app. Set up a POP / SMTP account and point the POP one at localhost 8181, TLS on, password auth.
```console
./mitmdump --set termlog_verbosity=debug --mode reverse:https://pop.gmail.com:995 --set connection_strategy=eager -w mail_debug --set flow_detail=3 -p 8181 -vvv --set proxy_debug=true
Proxy server listening at http://*:8181
[::1]:65101: client connect
[::1]:65101: >> Start({})
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: >! DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:65101: [nextlayer] ReverseProxy()
[::1]:65101: >> Start({})
[::1]:65101: << OpenConnection({'connection': Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'pop.gmail.com', 'tls': True})})
[::1]:65101: << OpenConnection({'connection': Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'pop.gmail.com', 'tls': True})})
[::1]:65101: !> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >! DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: server connect pop.gmail.com (172.217.193.108:995)
[::1]:65101: >> Reply(OpenConnection({'connection': Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'peername': ('172.217.193.108', 995), 'sockname': ('192.168.86.222', 65102)})}),None)
[::1]:65101: >> Start({})
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'peername': ('172.217.193.108', 995), 'sockname': ('192.168.86.222', 65102)}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=None))
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'pee…
[::1]:65101: !> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >! DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208, 'peername': ('172.217.193.108', 995), 'sockname': ('192.168.86.222', 65102), 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=<OpenSSL.SSL.Connection object at 0x112e7ea30>)),None)
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…2c6973', 'address': ('pop.gmail.com', 995), 'state': <ConnectionState.OPEN: 3>, 'sni': 'pop.gmail.com', 'tls': True, 'timestamp_start': 1623947635.39981, 'timestamp_tcp_setup': 1623947635.4746208…
[::1]:65101: << SendData(server, b"\x16\x03\x01\x01.\x01\x00\x01*\x03\x03\xf5z4\x7fG\x08)(\x08SZ\xba\x9b\x9e\x9dD\xf0Ixw\xe7\x0e\x0e\x0b\x0e\x92,\xaeG[\x94\xcd p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x00:\x13\x02\x13\x03\x13\x01\xc0+\xc0/\xc0,\xc00\xcc\xa9\xcc\xa8\x00\x9e\x00\x9f\xcc\xaa\xc0#\xc0'\xc0\t\xc0\x13\xc0$\xc0(\xc0\n\xc0\x14\x00g\x00k\x00\x9c\x00\x9d\x00<\x00=\x00/\x005\x00\xff\x01\x00\x00\xa7\x00\x00\x00\x12\x00\x10\x00\x00\rpop.gmail.com\x00\x0b\x00\x04\x0…
[::1]:65101: << SendData(server, b"\x16\x03\x01\x01.\x01\x00\x01*\x03\x03\xf5z4\x7fG\x08)(\x08SZ\xba\x9b\x9e\x9dD\xf0Ixw\xe7\x0e\x0e\x0b\x0e\x92,\xaeG[\x94\xcd p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x00:\x13\x02\x13…
[::1]:65101: !> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\x97jY\x87\xf0\xe4C\x8c?\xd1\x98>\x0b\x16\x11\xf9\xcfz\xe5R\x85\x83p\xd1\xa7e\xeb\x81N,8I p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x13\x02\x00\x00.\x003\x00$\x00\x1d\x00 \xd1,\xfc\xcaeS\x9c`0tQ\xa8\x8d\xbd2\xb0b\xae\x8a\xae\xac\x8cAS\xe7\x153\xebl2\x8cB\x00+\x00\x02\x03\x04\x14\x03\x03\x00\x01\x01\x17\x03\x03\t\xc5\x0e\xcfDu\n\xca\xccv%\xe2\xc5\xd3!\xad\x9a\xe6\xf9\x90\xda6\x06,5\xeb a\xe6~\xd…
[::1]:65101: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\x97jY\x87\xf0\xe4C\x8c?\xd1\x98>\x0b\x16\x11\xf9\xcfz\xe5R\x85\x83p\xd1\xa7e\xeb\x81N,8I p\xfd`\xa3\xf9/\x9e\x11\xa5*ias\xf74\x1cgO\xbc\xba\xbc\xfd\xa2\xf2\x02(\xef4\x1f\xf2\x83\xa5\x13\x02\x…
[::1]:65101: [tls] tls established: Server(pop.gmail.com:995, state=open, tls, src_port=65102)
[::1]:65101: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00Er\xef\xed\xcd=\x8f7\x8b\nl\xb2Sn\xdc\xc7*i\x05\xa5\xb7\x02%Ur}\xade\x05\xa1\x0e\x8ed\xa5\xec\x9d\x8b\x1a9&O\xac)*\xbe\xf1]\xce\x1a{\xf8\x95\xf9\x89\xc6\xe4\x14\x94\xacy/\xc8D\xa8\xb3e\x1do\x85\xaa')
[::1]:65101: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00Er\xef\xed\xcd=\x8f7\x8b\nl\xb2Sn\xdc\xc7*i\x05\xa5\xb7\x02%Ur}\xade\x05\xa1\x0e\x8ed\xa5\xec\x9d\x8b\x1a9&O\xac)*\xbe\xf1]\xce\x1a{\xf8\x95\xf9\x89\xc6\xe4\x14\x94\xacy/\xc8D\xa8\xb3e\x1do\x85\…
[::1]:65101: >> Start({})
[::1]:65101: >> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: << NextLayerHook(data=NextLayer:None)
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive pop.gmail.com b'')),None)
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive pop.gmail.com b'')),None)
[::1]:65101: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive pop.gmail.com b'')),None)
[::1]:65101: [nextlayer] ServerTLSLayer(inactive pop.gmail.com b'')
[::1]:65101: >> Start({})
[::1]:65101: >> Start({})
[::1]:65101: >> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0\'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x00\x06\x00\x17\x0…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcbysc5\x8a \n\xf5$\tc\x81"\xa2\xf8\x90Y\xa1\xfb\xbep\x1b\x14\x8c[9N?\x87\xd9 \x8a^\x00=\xd5\x9c\xf4x\x9c\x96P\x88Y\xd6\xf1y\xc1b\xdd\xc1D\xbb\x00M\xbffE\xb9_\xd1Y\xc9\x00:\x00\xff\xc0…
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=False))
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x112e57880>, establish_server_tls_first=True)),None)
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=None))
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'al…
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'al…
[::1]:65101: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'al…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x112e57880>, ssl_conn=<OpenSSL.SSL.Connection object at 0x112ea0550>)),None)
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost…
[::1]:65101: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…d71470', 'peername': ('::1', 65101, 0, 0), 'sockname': ('::1', 8181, 0, 0), 'timestamp_start': 1623947635.394167, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01\x00\x01\x00\x00\x0b\x00\x04\x03\x00\x01\x02\x00\x17\x00\x00\x16\x03\x03\x03-\x0b\x00\x03)\x00\x03&\x00\x03#0\x82\x03\x1f0\x82\x02\x07\xa0\x03\x02\x01\x02\x02\x14?k\xa4\x82\x87\xc9aA\x14\x80\xf7\x99Nd\x00\xa5DL}.0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x0…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01…
[::1]:65101: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03\x0b\xb1\x94\x7f\xf3tQ$P\xc1\x92\xfeq%\xa1\xea\xb3F+-.\xb2\xf8\xd8DOWNGRD\x01 `\xd1\xdc\xe2\xd9\xc9\x00\xd0R\x828\x13\xddn7\xd7?\x14\xd6+\x95\x8e\x926W\xa5\t\xb7\xebzR\xf9\xc0/\x00\x00\x11\xff\x01…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xc3\xb1\x19\x14\x01v\xeb\xa3^\x14+\xcc\xd7\x9b\xeb:\xe3\xe0<\x1f\xd3p\xb8I&\xc4\x01\xd8\xd0&3\xa9x}\xc7\xefye\xf8\xc2')
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x…
[::1]:65101: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04I\x1e\xfa~\xd6\xf6\xeb\xe7\x1b\xdc\xa6_\xba\x97D\xa7\xf8v(\x92\x12\xdc\xdf\xe8|\x87\x91\xac\\(iJ,\xb3x$\x89h\x0fY\xfc\xfc:\x95d\xe4\xffK4A\x9d\xecV\xc0\xef\x81\x0e\x11M\xaa\xb8\x0e\xaek\x14\x03\x…
[::1]:65101: [tls] tls established: Client([::1]:65101, state=open, tls)
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(>\x95\x10=\xc5\xfb\xca|s2t\x0fvZ\xaf\xc7\xa5\ny\xfd\xf5\x93\x95\x02\x10O\x0bo\xfe\xc4\x01\xd9\x82\xb7A2;\x90\x13\xac')
[::1]:65101: >> Start({})
[::1]:65101: >> DataReceived(server, b"\x17\x03\x03\x02\x15\x1f\x0f\xb7\xef\x12\xe1\x122~\xf0\x98\xe3\x1c2\x99\x88\x84\x96\xe2]n\x9c\xf6P\x12C\x825\x83\x1c>_\xa6\xa9\x90\x8f\x92\xc8Q\x1e#\xef\xe5.\xfa\xf6L\x7f\xc7Q\x83d\xe2\x01\xab)\xa1\xbd\xd8\xb2\xe7\xfa\xdcM\xfe\xde'\xb9\xe5\x07\n\xdcR_\xbb\xc2\x81\x84k/\xe3\xd0N\xcc\x98\x03\xc7\xa4g\xa6\xe8_A$\xd8\xbf[\x95\xe1s\xea\xc6\xbb\xbe\xdb\x7f\x8d\x04[\xe8\xe30\x8a\xc6\x84\x1c\x0b\x88\x95\xcc\x13u$s\x1a\x01\xeb\xcf\xf9\r/\xdf\x19\xa8a\x17w\xc5\xdf\xe7!\\c\x1c\xc9\x9a\xb2\x0e…
[::1]:65101: >> DataReceived(server, b"\x17\x03\x03\x02\x15\x1f\x0f\xb7\xef\x12\xe1\x122~\xf0\x98\xe3\x1c2\x99\x88\x84\x96\xe2]n\x9c\xf6P\x12C\x825\x83\x1c>_\xa6\xa9\x90\x8f\x92\xc8Q\x1e#\xef\xe5.\xfa\xf6L\x7f\xc7Q\x83d\xe2\x01\xab)\xa1\xbd\xd8\xb2\xe7\xfa\xdcM\xfe\xde…
[::1]:65101: >> DataReceived(server, b'+OK Gpop ready for requests from 24.137.254.57 p23mb49974932uao\r\n')
[::1]:65101: mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 279, in server_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 240, in receive_data
File "mitmproxy/proxy/layers/tls.py", line 306, in event_to_child
File "mitmproxy/proxy/tunnel.py", line 104, in event_to_child
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 225, in receive_data
AttributeError: 'NoneType' object has no attribute 'bio_write'
```
Thanks, this is super helpful! I'll take a look later today.
also crashing on SMTP. from the mail client:
```console
INITIATING CONNECTION Jun 17 12:49:46.234 host:localhost -- port:8282 -- socket:0x0 -- thread:0x600003691340
CONNECTED Jun 17 12:49:46.479 [kCFStreamSocketSecurityLevelTLSv1_2] -- host:localhost -- port:8282 -- socket:0x600000ac0180 -- thread:0x600003691340
```
mitmdump:
```console
% ./mitmdump --mode reverse:https://smtp.gmail.com:465 --set connection_strategy=eager -p8282 -vvv --set proxy_debug=true
Proxy server listening at http://*:8282
[::1]:50064: client connect
[::1]:50064: >> Start({})
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:50064: [nextlayer] ReverseProxy()
[::1]:50064: >> Start({})
[::1]:50064: << OpenConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50064: << OpenConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50064: server connect smtp.gmail.com (172.217.204.109:465)
[::1]:50064: >> Reply(OpenConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065)})}),None)
[::1]:50064: >> Start({})
[::1]:50064: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065)}), context=<mitmproxy.proxy.context.Context object at 0x10f8cb850>, ssl_conn=None))
[::1]:50064: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, '…
[::1]:50064: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065), 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8cb850>, ssl_conn=<OpenSSL.SSL.Connection object at 0x10f8f4490>)),None)
[::1]:50064: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521…
[::1]:50064: << SendData(server, b"\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\x19\xe5\xff\x80d*\x14\x06\x1e\xf1\r\xe3\xb7\xf6\x7f\xe5G\xceH\x82bre\xc9\xf1B\x82#\xa5\x00\xfb\x89 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe4\xda\xd4\xdd\x00:\x13\x02\x13\x03\x13\x01\xc0+\xc0/\xc0,\xc00\xcc\xa9\xcc\xa8\x00\x9e\x00\x9f\xcc\xaa\xc0#\xc0'\xc0\t\xc0\x13\xc0$\xc0(\xc0\n\xc0\x14\x00g\x00k\x00\x9c\x00\x9d\x00<\x00=\x00/\x005\x00\xff\x01\x00\x00\xa8\x00\x00\x00\x13\x00\x11\x00\x00\x0esmtp.gmail…
[::1]:50064: << SendData(server, b"\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\x19\xe5\xff\x80d*\x14\x06\x1e\xf1\r\xe3\xb7\xf6\x7f\xe5G\xceH\x82bre\xc9\xf1B\x82#\xa5\x00\xfb\x89 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe4\xda\xd4\…
[::1]:50064: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\xa6\xc4\x8b,\n\x16\xc0\xba\xa7\xd3v\xc1\x89k\xe7\xc6\xfb\xb5\xcb\x9b3\xabac\x95\x00\xde\xa1\x1bm\xa5\x94 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe4\xda\xd4\xdd\x13\x02\x00\x00.\x003\x00$\x00\x1d\x00 \x94Ry\x13\xeb\xe4\xf3\r\x81\xb6\x90\xff\xe8\x12X\x16\x12\xab)\x93|}\xb5\xf0U\x1f\xa20I\xd3\xbd\x19\x00+\x00\x02\x03\x04\x14\x03\x03\x00\x01\x01\x17\x03\x03\t\xc7\xda\xb3\x8f\xe4N#\x10m\xb2\xaf\xb3\xecN\…
[::1]:50064: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\xa6\xc4\x8b,\n\x16\xc0\xba\xa7\xd3v\xc1\x89k\xe7\xc6\xfb\xb5\xcb\x9b3\xabac\x95\x00\xde\xa1\x1bm\xa5\x94 G\x88\xbe\xb3\x06\x9c\x9d\x1f\xd6xO\x8eC+\x08|b\xbb\xbaa\t\xee\xa1\xea\xf1\xc5P\xaf\xe…
[::1]:50064: [tls] tls established: Server(smtp.gmail.com:465, state=open, tls, src_port=50065)
[::1]:50064: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\x15\xc2j\xf0\x90Q\x1d\xed\x83\x98\x84\xae\x16\xbc\x7f\xee\xedk\xf7\x8d)2^}\rM\x95\xda\x19\xc2\nX\xd0a\x04\xcc\xbbK\xff\xda\xbct\x1a&}:m\xedc\x0b\n\xda*\x88\x19\xe6\xa8\xf9\x82\xf3\xe4\xd7\xd3\xf3Q"\xd5\x1e\xba')
[::1]:50064: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\x15\xc2j\xf0\x90Q\x1d\xed\x83\x98\x84\xae\x16\xbc\x7f\xee\xedk\xf7\x8d)2^}\rM\x95\xda\x19\xc2\nX\xd0a\x04\xcc\xbbK\xff\xda\xbct\x1a&}:m\xedc\x0b\n\xda*\x88\x19\xe6\xa8\xf9\x82\xf3\xe4\xd7\xd3\…
[::1]:50064: >> Start({})
[::1]:50064: >> DataReceived(server, b'\x17\x03\x03\x02\x15cc]\x846\xa1\x15\xd4lZC"hr\xd6\xfb"\xa6\x14S\xa752V}F@\x8d\x8eg\xde\xaf\x15M\xf4r\x86F\x0em\rE[}w\x94^?f/\x88\x89\xce,\xbf!\n\xd8\x87\r\xe0\x01\xa4T][B\xa0\x7fu\x7f\xbb-\x1e\xfaU\x1f\xa7\x99\xa8o$\x899\x15k\x9a\xf1_Q\xb3\x17\x00\xcbr\xd7\x8f\xeb\xedb.<\xc5\x1c\xd4\x81\xd2G\xf8.\x00U$\xf4\xf0\xaa\x8b\xdf~Nd\x04\xdaL\xd5\xb3-\xcetJ\xa35B\x10^\xe0\x12!\xff$vy\xeb\xab8\t\x04d\x92B\xb2\xbe,\xc7*\x86\xe9+N*\x85_\xde\x91Z\n\xf8}\x95Wl\xcc\x91\xc2\xc9\xa3J59\xe7}e\xae\x…
[::1]:50064: >> DataReceived(server, b'\x17\x03\x03\x02\x15cc]\x846\xa1\x15\xd4lZC"hr\xd6\xfb"\xa6\x14S\xa752V}F@\x8d\x8eg\xde\xaf\x15M\xf4r\x86F\x0em\rE[}w\x94^?f/\x88\x89\xce,\xbf!\n\xd8\x87\r\xe0\x01\xa4T][B\xa0\x7fu\x7f\xbb-\x1e\xfaU\x1f\xa7\x99\xa8o$\x899\x15k\x9a…
[::1]:50064: >> DataReceived(server, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: << NextLayerHook(data=NextLayer:None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:50064: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:50064: [nextlayer] TCPLayer(state: start)
[::1]:50064: >> Start({})
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:50064: >! DataReceived(server, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:50064: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:50064: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:50064: !> DataReceived(server, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:50064 <- tcp <- smtp.gmail.com:465
[::1]:50064: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: << SendData(client, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << SendData(client, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: << SendData(client, b'220 smtp.gmail.com ESMTP k15sm878177uaq.19 - gsmtp\r\n')
[::1]:50064: >> ConnectionClosed(connection=Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}))
[::1]:50064: >> ConnectionClosed(connection=Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}))
[::1]:50064: >> ConnectionClosed(connection=Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}))
[::1]:50064: << CloseConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065), 'alpn_offers': [], 'timestamp_tls_setup': 1623948574.6460001, 'alpn': b'', 'certificate_list': [<mitmproxy.certs.Cert object at 0x10f8f45b0>, <mitmproxy.certs.Cert object at 0x10f8f4640…
[::1]:50064: << CloseConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peern…
[::1]:50064: << CloseConnection({'connection': Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peern…
[::1]:50064: half-closing Server(smtp.gmail.com:465, state=open, tls, src_port=50065)
[::1]:50064: >> ConnectionClosed(connection=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50065), 'alpn_offers': [], 'timestamp_tls_setup': 1623948574.6460001, 'alpn': b'', 'certificate_list': [<mitmproxy.certs.Cert object at 0x10f8f45b0>, <mitmproxy.certs.Cert object at 0x10f8f4640>…
[::1]:50064: >> ConnectionClosed(connection=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peerna…
[::1]:50064: >> ConnectionClosed(connection=Server({'id': '…17df85', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948574.1959229, 'timestamp_tcp_setup': 1623948574.521889, 'peerna…
[::1]:50064: << CloseConnection({'connection': Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}), 'half_close': False})
[::1]:50064: << CloseConnection({'connection': Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}), 'half_close': False})
[::1]:50064: << CloseConnection({'connection': Client({'id': '…529a3f', 'peername': ('::1', 50064, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948574.192099, 'state': <ConnectionState.CAN_WRITE: 2>, 'reply': None}), 'half_close': False})
[::1]:50064: << TcpEndHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpEndHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: << TcpEndHook(flow=<TCPFlow (1 messages)>)
[::1]:50064: server disconnect smtp.gmail.com (172.217.204.109:465)
[::1]:50064: client disconnect
[::1]:50064: >> Reply(TcpEndHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpEndHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: >> Reply(TcpEndHook(flow=<TCPFlow (1 messages)>),None)
[::1]:50064: closing transports...
[::1]:50064: transports closed!
[::1]:50104: client connect
[::1]:50104: >> Start({})
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: >! DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:50104: [nextlayer] ReverseProxy()
[::1]:50104: >> Start({})
[::1]:50104: << OpenConnection({'connection': Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50104: << OpenConnection({'connection': Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.CLOSED: 0>, 'sni': 'smtp.gmail.com', 'tls': True})})
[::1]:50104: !> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >! DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: server connect smtp.gmail.com (172.217.204.109:465)
[::1]:50104: >> Reply(OpenConnection({'connection': Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50105)})}),None)
[::1]:50104: >> Start({})
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50105)}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=None))
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'p…
[::1]:50104: !> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >! DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.336297, 'peername': ('172.217.204.109', 465), 'sockname': ('192.168.86.222', 50105), 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=<OpenSSL.SSL.Connection object at 0x10f9173d0>)),None)
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Server({'id': '…ef1b92', 'address': ('smtp.gmail.com', 465), 'state': <ConnectionState.OPEN: 3>, 'sni': 'smtp.gmail.com', 'tls': True, 'timestamp_start': 1623948586.253964, 'timestamp_tcp_setup': 1623948586.3362…
[::1]:50104: << SendData(server, b'\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\xcf\xd6\xdc\xb2\xd2\x17\xc1R\xdf\x1c\xb7\x1c\xa3\xd7f\xef\xb7R\x02a-\xfb\xb6c\xa2\xecn\x81\xba\xf9\x88\xc6 -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\xa1#q\x00:\x13\x02\x13\x03\x13\x01\xc0+\xc0/\xc0,\xc00\xcc\xa9\xcc\xa8\x00\x9e\x00\x9f\xcc\xaa\xc0#\xc0\'\xc0\t\xc0\x13\xc0$\xc0(\xc0\n\xc0\x14\x00g\x00k\x00\x9c\x00\x9d\x00<\x00=\x00/\x005\x00\xff\x01\x00\x00\xa8\x00\x00\x00\x13\x00\x11\x00\x00\x0esmtp.gma…
[::1]:50104: << SendData(server, b'\x16\x03\x01\x01/\x01\x00\x01+\x03\x03\xcf\xd6\xdc\xb2\xd2\x17\xc1R\xdf\x1c\xb7\x1c\xa3\xd7f\xef\xb7R\x02a-\xfb\xb6c\xa2\xecn\x81\xba\xf9\x88\xc6 -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\x…
[::1]:50104: !> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\\\x93\x98\x8eM\x06\x98\x90I\xe8Z`\xb1\xf0V\x10\xd9"\x9aME\n\xfe\xa0\xb6\xb6\xa9\xc6\xe8\xce\xa0e -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\xa1#q\x13\x02\x00\x00.\x003\x00$\x00\x1d\x00 K\x03\xcd6\x88g\xf7\x90\xd8\xc4\x9f\x11\xf8\xd9[_egOb\x881)\x80\\\xc6}0L\x83\x01\x15\x00+\x00\x02\x03\x04\x14\x03\x03\x00\x01\x01\x17\x03\x03\t\xc5\xb2\x92\x97\x83\xf6bS\xd3\x95C\x17\xe5\x1d%\xd2\xc2W\x16\xa6\x05\xdd\x…
[::1]:50104: >> DataReceived(server, b'\x16\x03\x03\x00z\x02\x00\x00v\x03\x03\\\x93\x98\x8eM\x06\x98\x90I\xe8Z`\xb1\xf0V\x10\xd9"\x9aME\n\xfe\xa0\xb6\xb6\xa9\xc6\xe8\xce\xa0e -~\x16\xd6\xd2\xc9\x10\x88`\xeeq\x1dG\x8c\xb6\xed"\x9a\x9b\xb6\x15\x12\xdb\xd7i\x89k(J\xa1#q\x…
[::1]:50104: [tls] tls established: Server(smtp.gmail.com:465, state=open, tls, src_port=50105)
[::1]:50104: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\xa8\xfa\xaeH\xa8J\x85\xb6w4S\xc1\xa3\xebT"\x00*i\xab\x04a\xc4\x04,\xcc\xfb\xbb\xc5d\xe1\xc3\x81{\\\xd0<\x16s\xf7\xb2!\xb93\n=\x85!\xb1\x9d\xc0\xb6\xfb\xf3\xcd7\xa9\xb8\xde^{.\xd2\xf0\xaa\xeb\x15\x98\xe2')
[::1]:50104: << SendData(server, b'\x14\x03\x03\x00\x01\x01\x17\x03\x03\x00E\xa8\xfa\xaeH\xa8J\x85\xb6w4S\xc1\xa3\xebT"\x00*i\xab\x04a\xc4\x04,\xcc\xfb\xbb\xc5d\xe1\xc3\x81{\\\xd0<\x16s\xf7\xb2!\xb93\n=\x85!\xb1\x9d\xc0\xb6\xfb\xf3\xcd7\xa9\xb8\xde^{.\xd2\xf0\xaa\xeb\x…
[::1]:50104: >> Start({})
[::1]:50104: >> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: << NextLayerHook(data=NextLayer:None)
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive smtp.gmail.com b'')),None)
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive smtp.gmail.com b'')),None)
[::1]:50104: >> Reply(NextLayerHook(data=NextLayer:ServerTLSLayer(inactive smtp.gmail.com b'')),None)
[::1]:50104: [nextlayer] ServerTLSLayer(inactive smtp.gmail.com b'')
[::1]:50104: >> Start({})
[::1]:50104: >> Start({})
[::1]:50104: >> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1U\x00:\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0\n\xc0\t\xc0\x08\xc00\xc0/\xc0(\xc0'\xc0\x14\xc0\x13\xc0\x12\x00\x9f\x00\x9e\x00k\x00g\x009\x003\x00\x16\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00K\x00\x00\x00\x0e\x00\x0c\x00\x00\tlocalhost\x00\n\x00\x08\x…
[::1]:50104: >> DataReceived(client, b"\x16\x03\x01\x00\xd2\x01\x00\x00\xce\x03\x03`\xcb}*\x90d\xdd\xd1\x01\xdbT6\x80\x1a\xe3y\x9c\xa5a\xdd\x18\xa6}\xc5<\x9a\xa6\x93\xb8\xf9\x1f \xbb0\x1f]\xc3,1=\x8bb\x8e9\xf3\\\x18\xfb\xe8\x83\xc1\t\xed\xa0\xad\x85\xbc*\x18.\x08;\xd1…
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: << TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=False))
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: >> Reply(TlsClienthelloHook(data=ClientHelloData(context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, establish_server_tls_first=True)),None)
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=None))
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'a…
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'a…
[::1]:50104: << TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'a…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhost', 'alpn_offers': []}), context=<mitmproxy.proxy.context.Context object at 0x10f8ea970>, ssl_conn=<OpenSSL.SSL.Connection object at 0x10f928e80>)),None)
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhos…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhos…
[::1]:50104: >> Reply(TlsStartHook(data=TlsStartData(conn=Client({'id': '…1b9fc8', 'peername': ('::1', 50104, 0, 0), 'sockname': ('::1', 8282, 0, 0), 'timestamp_start': 1623948586.2467752, 'state': <ConnectionState.OPEN: 3>, 'reply': None, 'tls': True, 'sni': 'localhos…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00\x11\xff\x01\x00\x01\x00\x00\x0b\x00\x04\x03\x00\x01\x02\x00\x17\x00\x00\x16\x03\x03\x03/\x0b\x00\x03+\x00\x03(\x00\x03%0\x82\x03!0\x82\x02\t\xa0\x03\x02\x01\x02\x02\x14\x1b\xbcbs\x95tRF_\x88d\xee\xb4fZ\xaf\x8e}\xfa/0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x0…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00…
[::1]:50104: << SendData(client, b'\x16\x03\x03\x00]\x02\x00\x00Y\x03\x03*\x8e\xcd\xd4\xb3+E\xd49v\x05s\xb2\xcd\xa3\xfa\xc4\xce!\xea_\x8b"IDOWNGRD\x01 \xdd\x03\xbcu`\xa0\x1f\xaf\xb1\xdc\x15g\xeb\x15\xa3\xf8\x9e\xb2q\x9e\xccA\xd9\xb0\x1e3\t\x87\xa8\xd4\x93?\xc0/\x00\x00…
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(L\x11|E\xa4\xc2\x84\xb0\xd4c\xa7"F\x11*\\\x11~\xa8o\xf0"\x9e\x80^-e\x86\xf8\x10\xa2\xe2_\xf8\x0f%\xd2\x08&\xcf')
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00…
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00…
[::1]:50104: >> DataReceived(client, b'\x16\x03\x03\x00F\x10\x00\x00BA\x04\xf5\xfd\xd2\xb8\xe4\x07cYT\x1f\xe6\xd2>\xd3\xa2\xa0Z\x82\xee\xadi)|\x0f?\xd2\xe6\xf0#\x8erY@r1\x9a\xe1T\xbc\xe6K\xb1\x0f\xf0\xa3\x1f\xcc\xa3"\xcd\x869{\xc6ap\xb9\x89j&\xc9~\xde\'\x14\x03\x03\x00…
[::1]:50104: [tls] tls established: Client([::1]:50104, state=open, tls)
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: << SendData(client, b'\x14\x03\x03\x00\x01\x01\x16\x03\x03\x00(\xd0k\x1dCX\x84C\x12t\xd8\xd6K\xda\xa0\x02s\xb6h\t?J\xe8\x15\xeb\xda\xf0\xe1\xeaZ\n\xa3M#@=\x16\xa7:\xbc\xec')
[::1]:50104: >> Start({})
[::1]:50104: >> DataReceived(server, b'\x17\x03\x03\x02\x15\xb5\xb7\xb2\xd5\x0e\x8f\xd3\x0f\x87\xd2\\.\xbe\x03V\xb1\x9d_\x08\x8de$\xee\xb7\\L*\'Q\xe9\r\xb2\x04\x05\x04\xc05\xa1V;\x859\xdbq\xa2\xbd\xe8%\xef\x1a\xe7ii\x94kp\xfb\xed\xee\x93\xa8_\x9eR\x1d\n\xd1D\xe4\x91\xc8\xf4\x16\xf8\xf9\xfb[:\x82r"[\xa4\x89\x10[w6\x99\xe5\xa5\xe9\x0c\xf6\xc9n\x17\xc3\xd7v\x06\xd4\xc9\x06\xb7R>%\x81\x03\x9f5qI\t\x8b\xa14\x9e\x8e+\xdb\x1d\x9f<\xa0\x19+%\xd5;\xc2\xd3\xa0\x8c7\xa5\xfcWY0\xc9A\xeap\xa7kd\'-\xb3H\x9d\xbc\xe4$!C\xc4B\xadG\x89g\…
[::1]:50104: >> DataReceived(server, b'\x17\x03\x03\x02\x15\xb5\xb7\xb2\xd5\x0e\x8f\xd3\x0f\x87\xd2\\.\xbe\x03V\xb1\x9d_\x08\x8de$\xee\xb7\\L*\'Q\xe9\r\xb2\x04\x05\x04\xc05\xa1V;\x859\xdbq\xa2\xbd\xe8%\xef\x1a\xe7ii\x94kp\xfb\xed\xee\x93\xa8_\x9eR\x1d\n\xd1D\xe4\x91\xc…
[::1]:50104: >> DataReceived(server, b'220 smtp.gmail.com ESMTP e19sm712405uaa.16 - gsmtp\r\n')
[::1]:50104: mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 279, in server_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/layer.py", line 168, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 240, in receive_data
File "mitmproxy/proxy/layers/tls.py", line 306, in event_to_child
File "mitmproxy/proxy/tunnel.py", line 104, in event_to_child
File "mitmproxy/proxy/layer.py", line 144, in handle_event
File "mitmproxy/proxy/tunnel.py", line 72, in _handle_event
File "mitmproxy/proxy/layers/tls.py", line 225, in receive_data
AttributeError: 'NoneType' object has no attribute 'bio_write'
```
Fantastic, thanks! I can reproduce it now, which generally makes fixing much easier. :) | 2021-06-17T18:07:29 |
|
mitmproxy/mitmproxy | 4,654 | mitmproxy__mitmproxy-4654 | [
"4576"
] | 64961232e6addec4abb27835d1b4efd0cdb7bb10 | diff --git a/mitmproxy/io/compat.py b/mitmproxy/io/compat.py
--- a/mitmproxy/io/compat.py
+++ b/mitmproxy/io/compat.py
@@ -312,6 +312,10 @@ def convert_12_13(data):
def convert_13_14(data):
data["version"] = 14
data["comment"] = ""
+ # bugfix for https://github.com/mitmproxy/mitmproxy/issues/4576
+ if data.get("response", None) and data["response"]["timestamp_start"] is None:
+ data["response"]["timestamp_start"] = data["request"]["timestamp_end"]
+ data["response"]["timestamp_end"] = data["request"]["timestamp_end"] + 1
return data
| diff --git a/test/helper_tools/dumperview.py b/test/helper_tools/dumperview.py
--- a/test/helper_tools/dumperview.py
+++ b/test/helper_tools/dumperview.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
import click
from mitmproxy.addons import dumper
diff --git a/test/helper_tools/inspect_dumpfile.py b/test/helper_tools/inspect_dumpfile.py
--- a/test/helper_tools/inspect_dumpfile.py
+++ b/test/helper_tools/inspect_dumpfile.py
@@ -1,8 +1,9 @@
+#!/usr/bin/env python3
from pprint import pprint
import click
-from mitmproxy import tnetstring
+from mitmproxy.io import tnetstring
def read_tnetstring(input):
diff --git a/test/mitmproxy/data/dumpfile-018.mitm b/test/mitmproxy/data/dumpfile-018.mitm
--- a/test/mitmproxy/data/dumpfile-018.mitm
+++ b/test/mitmproxy/data/dumpfile-018.mitm
@@ -1,54 +1,4 @@
-7816:4:type;4:http;2:id;36:55367415-10f5-4938-b69f-8a523394f947;8:response;1851:15:timestamp_start;17:1482157524.361187^12:http_version;8:HTTP/1.1,7:content;1270:<!doctype html>
-<html>
-<head>
- <title>Example Domain</title>
-
- <meta charset="utf-8" />
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <style type="text/css">
- body {
- background-color: #f0f0f2;
- margin: 0;
- padding: 0;
- font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
-
- }
- div {
- width: 600px;
- margin: 5em auto;
- padding: 50px;
- background-color: #fff;
- border-radius: 1em;
- }
- a:link, a:visited {
- color: #38488f;
- text-decoration: none;
- }
- @media (max-width: 700px) {
- body {
- background-color: #fff;
- }
- div {
- width: auto;
- margin: 0 auto;
- border-radius: 0;
- padding: 1em;
- }
- }
- </style>
-</head>
-
-<body>
-<div>
- <h1>Example Domain</h1>
- <p>This domain is established to be used for illustrative examples in documents. You may use this
- domain in examples without prior coordination or asking for permission.</p>
- <p><a href="http://www.iana.org/domains/example">More information...</a></p>
-</div>
-</body>
-</html>
-,13:timestamp_end;17:1482157524.361187^11:status_code;3:200#6:reason;2:OK,7:headers;410:25:13:Accept-Ranges,5:bytes,]35:13:Cache-Control,14:max-age=604800,]28:12:Content-Type,9:text/html,]40:4:Date,29:Mon, 19 Dec 2016 14:25:24 GMT,]22:4:Etag,11:"359670651",]43:7:Expires,29:Mon, 26 Dec 2016 14:25:24 GMT,]50:13:Last-Modified,29:Fri, 09 Aug 2013 23:54:35 GMT,]27:6:Server,14:ECS (iad/18CB),]26:4:Vary,15:Accept-Encoding,]16:7:X-Cache,3:HIT,]25:17:x-ec-custom-error,1:1,]25:14:Content-Length,4:1270,]]}7:request;396:9:is_replay;5:false!17:first_line_format;8:relative;4:port;3:443#7:content;0:,12:stickycookie;5:false!6:method;3:GET,7:headers;82:29:10:User-Agent,11:curl/7.35.0,]26:4:Host,15:www.example.com,]15:6:Accept,3:*/*,]]15:timestamp_start;18:1482157523.9086578^12:http_version;8:HTTP/1.1,13:timestamp_end;18:1482157523.9086578^4:path;1:/,10:stickyauth;5:false!4:host;15:www.example.com,6:scheme;5:https,}7:version;13:1:0#2:18#1:2#]5:error;0:~11:intercepted;5:false!11:server_conn;5143:10:ip_address;56:8:use_ipv6;5:false!7:address;23:13:93.184.216.34;3:443#]}15:timestamp_start;18:1482157523.9086578^19:timestamp_tcp_setup;18:1482157524.0081189^15:ssl_established;4:true!14:source_address;57:8:use_ipv6;5:false!7:address;24:12:10.67.53.133;5:52775#]}19:timestamp_ssl_setup;17:1482157524.260993^4:cert;2122:-----BEGIN CERTIFICATE-----
+7780:6:marked;5:false!11:client_conn;216:19:timestamp_ssl_setup;18:1482157523.9086578^7:address;53:7:address;20:9:127.0.0.1;5:52774#]8:use_ipv6;5:false!}10:clientcert;0:~13:timestamp_end;0:~15:ssl_established;4:true!15:timestamp_start;18:1482157522.8949482^}11:server_conn;5143:3:sni;15:www.example.com;7:address;58:7:address;25:15:www.example.com;3:443#]8:use_ipv6;5:false!}3:via;2570:7:address;58:7:address;25:15:www.example.com;3:443#]8:use_ipv6;5:false!}13:timestamp_end;0:~4:cert;2122:-----BEGIN CERTIFICATE-----
MIIF8jCCBNqgAwIBAgIQDmTF+8I2reFLFyrrQceMsDANBgkqhkiG9w0BAQsFADBw
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMS8wLQYDVQQDEyZEaWdpQ2VydCBTSEEyIEhpZ2ggQXNz
@@ -82,7 +32,7 @@ ieqRbcuFjmqfyPmUv1U9QoI4TQikpw7TZU0zYZANP4C/gj4Ry48/znmUaRvy2kvI
l7gRQ21qJTK5suoiYoYNo3J9T+pXPGU7Lydz/HwW+w0DpArtAaukI8aNX4ohFUKS
wDSiIIWIWJiJGbEeIO0TIFwEVWTOnbNl/faPXpk5IRXicapqiII=
-----END CERTIFICATE-----
-,13:timestamp_end;0:~3:via;2570:15:ssl_established;4:true!19:timestamp_tcp_setup;18:1482157524.0081189^19:timestamp_ssl_setup;17:1482157524.260993^3:via;0:~3:sni;15:www.example.com;10:ip_address;56:8:use_ipv6;5:false!7:address;23:13:93.184.216.34;3:443#]}15:timestamp_start;18:1482157523.9086578^14:source_address;57:8:use_ipv6;5:false!7:address;24:12:10.67.53.133;5:52775#]}4:cert;2122:-----BEGIN CERTIFICATE-----
+,14:source_address;57:7:address;24:12:10.67.53.133;5:52775#]8:use_ipv6;5:false!}15:timestamp_start;18:1482157523.9086578^10:ip_address;56:7:address;23:13:93.184.216.34;3:443#]8:use_ipv6;5:false!}3:sni;15:www.example.com;3:via;0:~19:timestamp_ssl_setup;17:1482157524.260993^19:timestamp_tcp_setup;18:1482157524.0081189^15:ssl_established;4:true!}13:timestamp_end;0:~4:cert;2122:-----BEGIN CERTIFICATE-----
MIIF8jCCBNqgAwIBAgIQDmTF+8I2reFLFyrrQceMsDANBgkqhkiG9w0BAQsFADBw
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMS8wLQYDVQQDEyZEaWdpQ2VydCBTSEEyIEhpZ2ggQXNz
@@ -116,4 +66,54 @@ ieqRbcuFjmqfyPmUv1U9QoI4TQikpw7TZU0zYZANP4C/gj4Ry48/znmUaRvy2kvI
l7gRQ21qJTK5suoiYoYNo3J9T+pXPGU7Lydz/HwW+w0DpArtAaukI8aNX4ohFUKS
wDSiIIWIWJiJGbEeIO0TIFwEVWTOnbNl/faPXpk5IRXicapqiII=
-----END CERTIFICATE-----
-,13:timestamp_end;0:~7:address;58:8:use_ipv6;5:false!7:address;25:15:www.example.com;3:443#]}}7:address;58:8:use_ipv6;5:false!7:address;25:15:www.example.com;3:443#]}3:sni;15:www.example.com;}11:client_conn;216:15:timestamp_start;18:1482157522.8949482^15:ssl_established;4:true!13:timestamp_end;0:~10:clientcert;0:~7:address;53:8:use_ipv6;5:false!7:address;20:9:127.0.0.1;5:52774#]}19:timestamp_ssl_setup;18:1482157523.9086578^}6:marked;5:false!}
\ No newline at end of file
+,19:timestamp_ssl_setup;17:1482157524.260993^14:source_address;57:7:address;24:12:10.67.53.133;5:52775#]8:use_ipv6;5:false!}15:ssl_established;4:true!19:timestamp_tcp_setup;18:1482157524.0081189^15:timestamp_start;18:1482157523.9086578^10:ip_address;56:7:address;23:13:93.184.216.34;3:443#]8:use_ipv6;5:false!}}11:intercepted;5:false!5:error;0:~7:version;13:1:0#2:18#1:2#]7:request;396:6:scheme;5:https,4:host;15:www.example.com,10:stickyauth;5:false!4:path;1:/,13:timestamp_end;18:1482157523.9086578^12:http_version;8:HTTP/1.1,15:timestamp_start;18:1482157523.9086578^7:headers;82:29:10:User-Agent,11:curl/7.35.0,]26:4:Host,15:www.example.com,]15:6:Accept,3:*/*,]]6:method;3:GET,12:stickycookie;5:false!7:content;0:,4:port;3:443#17:first_line_format;8:relative;9:is_replay;5:false!}8:response;1815:7:headers;410:25:13:Accept-Ranges,5:bytes,]35:13:Cache-Control,14:max-age=604800,]28:12:Content-Type,9:text/html,]40:4:Date,29:Mon, 19 Dec 2016 14:25:24 GMT,]22:4:Etag,11:"359670651",]43:7:Expires,29:Mon, 26 Dec 2016 14:25:24 GMT,]50:13:Last-Modified,29:Fri, 09 Aug 2013 23:54:35 GMT,]27:6:Server,14:ECS (iad/18CB),]26:4:Vary,15:Accept-Encoding,]16:7:X-Cache,3:HIT,]25:17:x-ec-custom-error,1:1,]25:14:Content-Length,4:1270,]]6:reason;2:OK,11:status_code;3:200#13:timestamp_end;0:~7:content;1270:<!doctype html>
+<html>
+<head>
+ <title>Example Domain</title>
+
+ <meta charset="utf-8" />
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <style type="text/css">
+ body {
+ background-color: #f0f0f2;
+ margin: 0;
+ padding: 0;
+ font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
+
+ }
+ div {
+ width: 600px;
+ margin: 5em auto;
+ padding: 50px;
+ background-color: #fff;
+ border-radius: 1em;
+ }
+ a:link, a:visited {
+ color: #38488f;
+ text-decoration: none;
+ }
+ @media (max-width: 700px) {
+ body {
+ background-color: #fff;
+ }
+ div {
+ width: auto;
+ margin: 0 auto;
+ border-radius: 0;
+ padding: 1em;
+ }
+ }
+ </style>
+</head>
+
+<body>
+<div>
+ <h1>Example Domain</h1>
+ <p>This domain is established to be used for illustrative examples in documents. You may use this
+ domain in examples without prior coordination or asking for permission.</p>
+ <p><a href="http://www.iana.org/domains/example">More information...</a></p>
+</div>
+</body>
+</html>
+,12:http_version;8:HTTP/1.1,15:timestamp_start;0:~}2:id;36:55367415-10f5-4938-b69f-8a523394f947;4:type;4:http;}
\ No newline at end of file
| Dump files not standard across versions
#### Problem Description
Dump files generated by mitmdump 5.2 aren't compatible with 5.3.x or 6.x.x.
Whats worse is that they're partially compatible, somehow the newer versions read one request in the file and not the rest of it.
#### Proposal
I get that maintaining backward compatibility is super hard and don't expect the project to start doing this.
It would be nice if users were informed of intricacies like this one.
#### Alternatives
Versioning info in Dump files and an error message when newer versions try to read them would be great.
Backward compatibility would be the best option of course, but trying to debug something like this is very hard.
Hopefully too many people haven't spent time trying to figure this out.
| Old dumpfiles can generally be read with newer versions since mitmproxy 0.11 or so. If that doesn't work for a particular file it's a bug and we need more details. :)
Sure!
[This](https://github.com/amoghbl1/mitm-dumps/blob/master/example.dump) dump works fine with mitmdump 5.2 but not with versions after it. | 2021-06-24T07:43:16 |
mitmproxy/mitmproxy | 4,659 | mitmproxy__mitmproxy-4659 | [
"4655"
] | adab4d54f514ec40f30ff86eab8ff7e3392fffdf | diff --git a/mitmproxy/connection.py b/mitmproxy/connection.py
--- a/mitmproxy/connection.py
+++ b/mitmproxy/connection.py
@@ -91,6 +91,7 @@ class Connection(serializable.Serializable, metaclass=ABCMeta):
For server connections, this value may also be set to `True`, which means "use `Server.address`".
"""
+ timestamp_start: Optional[float]
timestamp_end: Optional[float] = None
"""*Timestamp:* Connection has been closed."""
timestamp_tls_setup: Optional[float] = None
diff --git a/mitmproxy/proxy/layers/tcp.py b/mitmproxy/proxy/layers/tcp.py
--- a/mitmproxy/proxy/layers/tcp.py
+++ b/mitmproxy/proxy/layers/tcp.py
@@ -70,7 +70,7 @@ def start(self, _) -> layer.CommandGenerator[None]:
if self.flow:
yield TcpStartHook(self.flow)
- if not self.context.server.connected:
+ if self.context.server.timestamp_start is None:
err = yield commands.OpenConnection(self.context.server)
if err:
if self.flow:
| diff --git a/test/mitmproxy/proxy/layers/test_tcp.py b/test/mitmproxy/proxy/layers/test_tcp.py
--- a/test/mitmproxy/proxy/layers/test_tcp.py
+++ b/test/mitmproxy/proxy/layers/test_tcp.py
@@ -1,7 +1,6 @@
import pytest
from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
-from mitmproxy.connection import ConnectionState
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import tcp
from mitmproxy.proxy.layers.tcp import TcpMessageInjected
@@ -19,7 +18,7 @@ def test_open_connection(tctx):
<< OpenConnection(tctx.server)
)
- tctx.server.state = ConnectionState.OPEN
+ tctx.server.timestamp_start = 1624544785
assert (
Playbook(tcp.TCPLayer(tctx, True))
<< None
diff --git a/test/mitmproxy/proxy/test_layer.py b/test/mitmproxy/proxy/test_layer.py
--- a/test/mitmproxy/proxy/test_layer.py
+++ b/test/mitmproxy/proxy/test_layer.py
@@ -52,7 +52,8 @@ def state_bar(self, event: events.Event) -> layer.CommandGenerator[None]:
<< commands.Log(" >! DataReceived(client, b'foo')", "debug")
>> tutils.reply(None, to=-3)
<< commands.Log(" >> Reply(OpenConnection({'connection': Server("
- "{'id': '…rverid', 'address': None, 'state': <ConnectionState.OPEN: 3>})}),None)", "debug")
+ "{'id': '…rverid', 'address': None, 'state': <ConnectionState.OPEN: 3>, "
+ "'timestamp_start': 1624544785})}),None)", "debug")
<< commands.Log(" !> DataReceived(client, b'foo')", "debug")
<< commands.Log("baz", "info")
diff --git a/test/mitmproxy/proxy/tutils.py b/test/mitmproxy/proxy/tutils.py
--- a/test/mitmproxy/proxy/tutils.py
+++ b/test/mitmproxy/proxy/tutils.py
@@ -193,8 +193,10 @@ def __bool__(self):
setattr(x, name, value())
if isinstance(x, events.OpenConnectionCompleted) and not x.reply:
x.command.connection.state = ConnectionState.OPEN
+ x.command.connection.timestamp_start = 1624544785
elif isinstance(x, events.ConnectionClosed):
x.connection.state &= ~ConnectionState.CAN_READ
+ x.connection.timestamp_end = 1624544787
self.actual.append(x)
try:
| AssertionError: File "mitmproxy/proxy/server.py", line 282, in server_event
#### Problem Description
I'm currently putting mitmproxy in front of an FTP server in reverse mode. The FTP server has a limit of five connections. If I try to connect a sixth time mitmproxy runs into the following assertion:
```
error: *.*.*.*:47774: mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 282, in server_event
AssertionError
```
https://github.com/mitmproxy/mitmproxy/blob/64961232e6addec4abb27835d1b4efd0cdb7bb10/mitmproxy/proxy/server.py#L282
#### Steps to reproduce the behavior:
FTP Server on port 10022 with a connection limit of 1:
```sh
docker run -it --rm -p 10022:21 -p 30000-30009:30000-30009 \
-e FTP_USER_NAME=prinzhorn \
-e FTP_USER_PASS=prinzhorn \
-e FTP_USER_HOME=/home/prinzhorn \
-e FTP_PASSIVE_PORTS=30000:30009 \
-e FTP_MAX_CLIENTS=1 \
-e "ADDED_FLAGS=-d -d" \
stilliard/pure-ftpd
```
Mitmproxy on 10021 in reverse:
```sh
./mitmproxy \
--ssl-insecure \
--listen-port 10021 \
--listen-host 0 \
--mode reverse:http://localhost:10022 \
--set connection_strategy=eager \
--set block_global=false \
--tcp-hosts '.*'
```
Now connect twice to 10021, e.g. I was using two FileZilla tabs. The second connection triggers the error.
#### System Information
```
Mitmproxy: 7.0.0.dev binary
Python: 3.9.5
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Linux-5.4.0-52-generic-x86_64-with-glibc2.31
```
I just downloaded this binary from wget https://snapshots.mitmproxy.org/branches/main/mitmproxy-main-linux.tar.gz
| Event log with `-vvv --set proxy_debug`:
```
Proxy server listening at http://*:10021
[::1]:57280: client connect
[::1]:57280: >> Start({})
[::1]:57280: << NextLayerHook(data=NextLayer:None)
[::1]:57280: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:57280: [nextlayer] ReverseProxy()
[::1]:57280: >> Start({})
[::1]:57280: << OpenConnection({'connection': Server({'id': '…ae9b46', 'address': ('localhost', 10022), 'state': <ConnectionState.CLOSED: 0>})})
[::1]:57280: << OpenConnection({'connection': Server({'id': '…ae9b46', 'address': ('localhost', 10022), 'state': <ConnectionState.CLOSED: 0>})})
[::1]:57280: server connect localhost ([::1]:10022)
[::1]:57280: >> Reply(OpenConnection({'connection': Server({'id': '…ae9b46', 'address': ('localhost', 10022), 'state': <ConnectionState.OPEN: 3>, 'timestamp_start': 1624542764.7953513, 'timestamp_tcp_setup': 1624542764.8006616, 'peername': ('::1', 10022, 0, 0), 'sockname': ('::1', 57281, 0, 0)})}),None)
[::1]:57280: >> Start({})
[::1]:57280: >> DataReceived(server, b'220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------\r\n220-You are user number 1 of 1 allowed.\r\n220-Local time is now 13:52. Server port: 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections are also welcome on this server.\r\n220 You will be disconnected after 15 minutes of inactivity.\r\n')
[::1]:57280: >> DataReceived(server, b'220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------\r\n220-You are user number 1 of 1 allowed.\r\n220-Local time is now 13:52. Server port: 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections…
[::1]:57280: << NextLayerHook(data=NextLayer:None)
[::1]:57280: << NextLayerHook(data=NextLayer:None)
[::1]:57280: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:57280: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:57280: [nextlayer] TCPLayer(state: start)
[::1]:57280: >> Start({})
[::1]:57280: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:57280: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:57280: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:57280: >! DataReceived(server, b'220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------\r\n220-You are user number 1 of 1 allowed.\r\n220-Local time is now 13:52. Server port: 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections are also welcome on this server.\r\n220 You will be disconnected after 15 minutes of inactivity.\r\n')
[::1]:57280: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:57280: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:57280: !> DataReceived(server, b'220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------\r\n220-You are user number 1 of 1 allowed.\r\n220-Local time is now 13:52. Server port: 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections are also welcome on this server.\r\n220 You will be disconnected after 15 minutes of inactivity.\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (1 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (1 messages)>),None)
[::1]:57280: << SendData(client, b'220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------\r\n220-You are user number 1 of 1 allowed.\r\n220-Local time is now 13:52. Server port: 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections are also welcome on this server.\r\n220 You will be disconnected after 15 minutes of inactivity.\r\n')
[::1]:57280: << SendData(client, b'220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------\r\n220-You are user number 1 of 1 allowed.\r\n220-Local time is now 13:52. Server port: 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections are…
[::1]:57280: >> DataReceived(client, b'AUTH TLS\r\n')
[::1]:57280: >> DataReceived(client, b'AUTH TLS\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (2 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (2 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (2 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (2 messages)>),None)
[::1]:57280: << SendData(server, b'AUTH TLS\r\n')
[::1]:57280: << SendData(server, b'AUTH TLS\r\n')
[::1]:57280: >> DataReceived(server, b'500 This security scheme is not implemented\r\n')
[::1]:57280: >> DataReceived(server, b'500 This security scheme is not implemented\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (3 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (3 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (3 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (3 messages)>),None)
[::1]:57280: << SendData(client, b'500 This security scheme is not implemented\r\n')
[::1]:57280: << SendData(client, b'500 This security scheme is not implemented\r\n')
[::1]:57280: >> DataReceived(client, b'AUTH SSL\r\n')
[::1]:57280: >> DataReceived(client, b'AUTH SSL\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (4 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (4 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (4 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (4 messages)>),None)
[::1]:57280: << SendData(server, b'AUTH SSL\r\n')
[::1]:57280: << SendData(server, b'AUTH SSL\r\n')
[::1]:57280: >> DataReceived(server, b'500 This security scheme is not implemented\r\n')
[::1]:57280: >> DataReceived(server, b'500 This security scheme is not implemented\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (5 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (5 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (5 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (5 messages)>),None)
[::1]:57280: << SendData(client, b'500 This security scheme is not implemented\r\n')
[::1]:57280: << SendData(client, b'500 This security scheme is not implemented\r\n')
[::1]:57280: >> DataReceived(client, b'USER prinzhorn\r\n')
[::1]:57280: >> DataReceived(client, b'USER prinzhorn\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (6 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (6 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (6 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (6 messages)>),None)
[::1]:57280: << SendData(server, b'USER prinzhorn\r\n')
[::1]:57280: << SendData(server, b'USER prinzhorn\r\n')
[::1]:57280: >> DataReceived(server, b'331 User prinzhorn OK. Password required\r\n')
[::1]:57280: >> DataReceived(server, b'331 User prinzhorn OK. Password required\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (7 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (7 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (7 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (7 messages)>),None)
[::1]:57280: << SendData(client, b'331 User prinzhorn OK. Password required\r\n')
[::1]:57280: << SendData(client, b'331 User prinzhorn OK. Password required\r\n')
[::1]:57280: >> DataReceived(client, b'PASS prinzhorn\r\n')
[::1]:57280: >> DataReceived(client, b'PASS prinzhorn\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (8 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (8 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (8 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (8 messages)>),None)
[::1]:57280: << SendData(server, b'PASS prinzhorn\r\n')
[::1]:57280: << SendData(server, b'PASS prinzhorn\r\n')
[::1]:57280: >> DataReceived(server, b'230 OK. Current directory is /\r\n')
[::1]:57280: >> DataReceived(server, b'230 OK. Current directory is /\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (9 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (9 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (9 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (9 messages)>),None)
[::1]:57280: << SendData(client, b'230 OK. Current directory is /\r\n')
[::1]:57280: << SendData(client, b'230 OK. Current directory is /\r\n')
[::1]:57280: >> DataReceived(client, b'SYST\r\n')
[::1]:57280: >> DataReceived(client, b'SYST\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (10 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (10 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (10 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (10 messages)>),None)
[::1]:57280: << SendData(server, b'SYST\r\n')
[::1]:57280: << SendData(server, b'SYST\r\n')
[::1]:57280: >> DataReceived(server, b'215 UNIX Type: L8\r\n')
[::1]:57280: >> DataReceived(server, b'215 UNIX Type: L8\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (11 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (11 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (11 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (11 messages)>),None)
[::1]:57280: << SendData(client, b'215 UNIX Type: L8\r\n')
[::1]:57280: << SendData(client, b'215 UNIX Type: L8\r\n')
[::1]:57280: >> DataReceived(client, b'FEAT\r\n')
[::1]:57280: >> DataReceived(client, b'FEAT\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (12 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (12 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (12 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (12 messages)>),None)
[::1]:57280: << SendData(server, b'FEAT\r\n')
[::1]:57280: << SendData(server, b'FEAT\r\n')
[::1]:57280: >> DataReceived(server, b'211-Extensions supported:\r\n EPRT\r\n IDLE\r\n MDTM\r\n SIZE\r\n MFMT\r\n REST STREAM\r\n MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;\r\n MLSD\r\n AUTH TLS\r\n PBSZ\r\n PROT\r\n UTF8\r\n TVFS\r\n ESTA\r\n PASV\r\n EPSV\r\n SPSV\r\r\n211 End.\r\n')
[::1]:57280: >> DataReceived(server, b'211-Extensions supported:\r\n EPRT\r\n IDLE\r\n MDTM\r\n SIZE\r\n MFMT\r\n REST STREAM\r\n MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;\r\n MLSD\r\n AUTH TLS\r\n PBSZ\r\n PROT\r\n UTF8\r\n TVFS\r\n ESTA\r…
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (13 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (13 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (13 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (13 messages)>),None)
[::1]:57280: << SendData(client, b'211-Extensions supported:\r\n EPRT\r\n IDLE\r\n MDTM\r\n SIZE\r\n MFMT\r\n REST STREAM\r\n MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;\r\n MLSD\r\n AUTH TLS\r\n PBSZ\r\n PROT\r\n UTF8\r\n TVFS\r\n ESTA\r\n PASV\r\n EPSV\r\n SPSV\r\r\n211 End.\r\n')
[::1]:57280: << SendData(client, b'211-Extensions supported:\r\n EPRT\r\n IDLE\r\n MDTM\r\n SIZE\r\n MFMT\r\n REST STREAM\r\n MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;\r\n MLSD\r\n AUTH TLS\r\n PBSZ\r\n PROT\r\n UTF8\r\n TVFS\r\n ESTA\r\n P…
[::1]:57280: >> DataReceived(client, b'OPTS UTF8 ON\r\n')
[::1]:57280: >> DataReceived(client, b'OPTS UTF8 ON\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (14 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (14 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (14 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (14 messages)>),None)
[::1]:57280: << SendData(server, b'OPTS UTF8 ON\r\n')
[::1]:57280: << SendData(server, b'OPTS UTF8 ON\r\n')
[::1]:57280: >> DataReceived(server, b'200 OK, UTF-8 enabled\r\n')
[::1]:57280: >> DataReceived(server, b'200 OK, UTF-8 enabled\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (15 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (15 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (15 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (15 messages)>),None)
[::1]:57280: << SendData(client, b'200 OK, UTF-8 enabled\r\n')
[::1]:57280: << SendData(client, b'200 OK, UTF-8 enabled\r\n')
[::1]:57280: >> DataReceived(client, b'PWD\r\n')
[::1]:57280: >> DataReceived(client, b'PWD\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (16 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (16 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (16 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (16 messages)>),None)
[::1]:57280: << SendData(server, b'PWD\r\n')
[::1]:57280: << SendData(server, b'PWD\r\n')
[::1]:57280: >> DataReceived(server, b'257 "/" is your current location\r\n')
[::1]:57280: >> DataReceived(server, b'257 "/" is your current location\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (17 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (17 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (17 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (17 messages)>),None)
[::1]:57280: << SendData(client, b'257 "/" is your current location\r\n')
[::1]:57280: << SendData(client, b'257 "/" is your current location\r\n')
[::1]:57280: >> DataReceived(client, b'TYPE I\r\n')
[::1]:57280: >> DataReceived(client, b'TYPE I\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (18 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (18 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (18 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (18 messages)>),None)
[::1]:57280: << SendData(server, b'TYPE I\r\n')
[::1]:57280: << SendData(server, b'TYPE I\r\n')
[::1]:57280: >> DataReceived(server, b'200 TYPE is now 8-bit binary\r\n')
[::1]:57280: >> DataReceived(server, b'200 TYPE is now 8-bit binary\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (19 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (19 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (19 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (19 messages)>),None)
[::1]:57280: << SendData(client, b'200 TYPE is now 8-bit binary\r\n')
[::1]:57280: << SendData(client, b'200 TYPE is now 8-bit binary\r\n')
[::1]:57280: >> DataReceived(client, b'EPSV\r\n')
[::1]:57280: >> DataReceived(client, b'EPSV\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (20 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (20 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (20 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (20 messages)>),None)
[::1]:57280: << SendData(server, b'EPSV\r\n')
[::1]:57280: << SendData(server, b'EPSV\r\n')
[::1]:57280: >> DataReceived(server, b'229 Extended Passive mode OK (|||30007|)\r\n')
[::1]:57280: >> DataReceived(server, b'229 Extended Passive mode OK (|||30007|)\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (21 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (21 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (21 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (21 messages)>),None)
[::1]:57280: << SendData(client, b'229 Extended Passive mode OK (|||30007|)\r\n')
[::1]:57280: << SendData(client, b'229 Extended Passive mode OK (|||30007|)\r\n')
[::1]:57280: >> DataReceived(client, b'MLSD\r\n')
[::1]:57280: >> DataReceived(client, b'MLSD\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (22 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (22 messages)>)
[::1]:57280 -> tcp -> localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (22 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (22 messages)>),None)
[::1]:57280: << SendData(server, b'MLSD\r\n')
[::1]:57280: << SendData(server, b'MLSD\r\n')
[::1]:57280: >> DataReceived(server, b'150 Accepted data connection\r\n226-Options: -a -l \r\n226 2 matches total\r\n')
[::1]:57280: >> DataReceived(server, b'150 Accepted data connection\r\n226-Options: -a -l \r\n226 2 matches total\r\n')
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (23 messages)>)
[::1]:57280: << TcpMessageHook(flow=<TCPFlow (23 messages)>)
[::1]:57280 <- tcp <- localhost:10022
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (23 messages)>),None)
[::1]:57280: >> Reply(TcpMessageHook(flow=<TCPFlow (23 messages)>),None)
[::1]:57280: << SendData(client, b'150 Accepted data connection\r\n226-Options: -a -l \r\n226 2 matches total\r\n')
[::1]:57280: << SendData(client, b'150 Accepted data connection\r\n226-Options: -a -l \r\n226 2 matches total\r\n')
[::1]:57283: client connect
[::1]:57283: >> Start({})
[::1]:57283: << NextLayerHook(data=NextLayer:None)
[::1]:57283: >> Reply(NextLayerHook(data=NextLayer:ReverseProxy()),None)
[::1]:57283: [nextlayer] ReverseProxy()
[::1]:57283: >> Start({})
[::1]:57283: << OpenConnection({'connection': Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CLOSED: 0>})})
[::1]:57283: << OpenConnection({'connection': Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CLOSED: 0>})})
[::1]:57283: server connect localhost ([::1]:10022)
[::1]:57283: >> Reply(OpenConnection({'connection': Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.OPEN: 3>, 'timestamp_start': 1624542780.254956, 'timestamp_tcp_setup': 1624542780.2567515, 'peername': ('::1', 10022, 0, 0), 'sockname': ('::1', 57284, 0, 0)})}),None)
[::1]:57283: >> Start({})
[::1]:57283: >> DataReceived(server, b'421 1 users (the maximum) are already logged in, sorry\r\n')
[::1]:57283: >> DataReceived(server, b'421 1 users (the maximum) are already logged in, sorry\r\n')
[::1]:57283: << NextLayerHook(data=NextLayer:None)
[::1]:57283: << NextLayerHook(data=NextLayer:None)
[::1]:57283: >> ConnectionClosed(connection=Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CAN_WRITE: 2>, 'timestamp_start': 1624542780.254956, 'timestamp_tcp_setup': 1624542780.2567515, 'peername': ('::1', 10022, 0, 0), 'sockname': ('::1', 57284, 0, 0)}))
[::1]:57283: >! ConnectionClosed(connection=Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CAN_WRITE: 2>, 'timestamp_start': 1624542780.254956, 'timestamp_tcp_setup': 1624542780.2567515, 'peername': ('::1', 10022, 0, 0), 'sockname': ('::1', 57284, 0, 0)}))
[::1]:57283: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:57283: >> Reply(NextLayerHook(data=NextLayer:TCPLayer(state: start)),None)
[::1]:57283: [nextlayer] TCPLayer(state: start)
[::1]:57283: >> Start({})
[::1]:57283: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:57283: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:57283: << TcpStartHook(flow=<TCPFlow (0 messages)>)
[::1]:57283: >! DataReceived(server, b'421 1 users (the maximum) are already logged in, sorry\r\n')
[::1]:57283: !> ConnectionClosed(connection=Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CAN_WRITE: 2>, 'timestamp_start': 1624542780.254956, 'timestamp_tcp_setup': 1624542780.2567515, 'peername': ('::1', 10022, 0, 0), 'sockname': ('::1', 57284, 0, 0)}))
[::1]:57283: >! ConnectionClosed(connection=Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CAN_WRITE: 2>, 'timestamp_start': 1624542780.254956, 'timestamp_tcp_setup': 1624542780.2567515, 'peername': ('::1', 10022, 0, 0), 'sockname': ('::1', 57284, 0, 0)}))
[::1]:57283: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:57283: >> Reply(TcpStartHook(flow=<TCPFlow (0 messages)>),None)
[::1]:57283: << OpenConnection({'connection': Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CAN_WRITE: 2>, 'timestamp_start': 1624542780.254956, 'timestamp_tcp_setup': 1624542780.2567515, 'peername': ('::1', 10022, 0, 0), 'sockname': ('::1', 57284, 0, 0)})})
[::1]:57283: << OpenConnection({'connection': Server({'id': '…3e6328', 'address': ('localhost', 10022), 'state': <ConnectionState.CAN_WRITE: 2>, 'timestamp_start': 1624542780.254956, 'timestamp_tcp_setup': 1624542780.2567515, 'peername': ('::1', 10022, 0, 0), 'sockname…
[::1]:57283: mitmproxy has crashed!
Traceback (most recent call last):
File "c:\users\user\git\mitmproxy\mitmproxy\proxy\server.py", line 282, in server_event
assert command.connection not in self.transports
AssertionError
``` | 2021-06-24T14:38:20 |
mitmproxy/mitmproxy | 4,660 | mitmproxy__mitmproxy-4660 | [
"4547"
] | ad7f1d11e457b297d31ea1cbe953876fd9efb8ae | diff --git a/mitmproxy/addons/tlsconfig.py b/mitmproxy/addons/tlsconfig.py
--- a/mitmproxy/addons/tlsconfig.py
+++ b/mitmproxy/addons/tlsconfig.py
@@ -171,7 +171,7 @@ def create_proxy_server_ssl_conn(self, tls_start: tls.TlsStartData) -> None:
else:
verify = net_tls.Verify.VERIFY_PEER
- if server.sni is True:
+ if server.sni is None:
server.sni = client.sni or server.address[0]
if not server.alpn_offers:
diff --git a/mitmproxy/connection.py b/mitmproxy/connection.py
--- a/mitmproxy/connection.py
+++ b/mitmproxy/connection.py
@@ -2,7 +2,7 @@
import warnings
from abc import ABCMeta
from enum import Flag
-from typing import Literal, Optional, Sequence, Tuple, Union
+from typing import Optional, Sequence, Tuple
from mitmproxy import certs
from mitmproxy.coretypes import serializable
@@ -85,10 +85,9 @@ class Connection(serializable.Serializable, metaclass=ABCMeta):
"""Ciphers accepted by the proxy server on this connection."""
tls_version: Optional[str] = None
"""The active TLS version."""
- sni: Union[str, Literal[True], None]
+ sni: Optional[str] = None
"""
The [Server Name Indication (SNI)](https://en.wikipedia.org/wiki/Server_Name_Indication) sent in the ClientHello.
- For server connections, this value may also be set to `True`, which means "use `Server.address`".
"""
timestamp_start: Optional[float]
@@ -144,8 +143,6 @@ class Client(Connection):
"""
The certificate used by mitmproxy to establish TLS with the client.
"""
- sni: Union[str, None] = None
- """The Server Name Indication sent by the client."""
timestamp_start: float
"""*Timestamp:* TCP SYN received"""
@@ -272,7 +269,6 @@ class Server(Connection):
timestamp_tcp_setup: Optional[float] = None
"""*Timestamp:* TCP ACK received."""
- sni: Union[str, Literal[True], None] = True
via: Optional[server_spec.ServerSpec] = None
"""An optional proxy server specification via which the connection should be established."""
| Simplify Server.sni
#### Problem Description
When a property has a mix of unrelated types it takes me more time than it should take to wrap my head around. To me this always smells like something could be simplified, but I guess that's something I have to get used to with Python? I'm talking about `Server.sni: Union[str, Literal[True], NoneType] = True` vs `Client.sni: Optional[str] = None`
> The Server Name Indication (SNI) sent in the ClientHello. For server connections, this value may also be set to True, which means "use Server.address".
Is this something that could be hidden under the hood? As a user I don't care. I just want the string that was used for sni. I don't want to replicate internal logic inside my addon.
#### Proposal
When SNI is used just duplicate `address[0]` into `sni`.
| server.sni will be set to server.address during the handshake, it will only be set to True before that. Does that help?
> Does that help?
Somewhat I guess. So that means in later hooks (e.g. `server_disconnected`) it is guaranteed to be either a string or `None`? I've seen this pattern more than once in mitmproxy, where a property is used to either hold a value or a sort of flag that like has a side effect on the meaning later in some internal parts of the code. I find it confusing. Could there be a (private?) boolean flag that does that job and `sni` is kept clean?
Is it correct that both of the current `tls_` hooks are too early for that? So `sni` could still be `True`? Or does SNI happen between `tls_start` and `tls_clienthello`?
Wait a second, isn't `tls_start` ambiguous? Is it the TLS start between client<->mitmproxy or mitmproxy<->server? Or does it fire for both? Since `TlsStartData` holds a generic `connection.Connection` I assume both? Maybe there needs to be `tls_clientstart` and `tls_serverstart`?
> Somewhat I guess. So that means in later hooks (e.g. server_disconnected) it is guaranteed to be either a string or None?
Yes, as long as you don't intentionally disable the TlsConfig addon somehow.
> Could there be a (private?) boolean flag that does that job and sni is kept clean?
I think you somewhat convinced me here. Let's make `sni` an `Optional[str]`. In `tlsconfig.py`, we just change the `if` statement here to `if server.sni is None:`
https://github.com/mitmproxy/mitmproxy/blob/438567f58c86ab13d721bd34f039fbddea52906f/mitmproxy/addons/tlsconfig.py#L166-L167
That should still cover all relevant cases. PRs welcome. 😊😇
> Is it correct that both of the current tls_ hooks are too early for that?
`tls_clienthello` is too early, SNI is then processed by the TlsConfig addon during `tls_start`. So it depends on the addon call order here.
> Wait a second, isn't tls_start ambiguous? Is it the TLS start between client<->mitmproxy or mitmproxy<->server? Or does it fire for both?
Both:
https://github.com/mitmproxy/mitmproxy/blob/438567f58c86ab13d721bd34f039fbddea52906f/mitmproxy/addons/tlsconfig.py#L114-L118
The fact that the only place where we are using this has a check _and_ you are requesting essentially the same, I'd be happy to change it and split it into two separate events. Again, PRs welcome. 😊😇
Overall this is excellent feedback on unpolished APIs, please keep it coming! 🍰
Nice, thanks for the details. I'm interested in making the PRs, but not right now. I'll self-assign the issue once I do to avoid conflicts. | 2021-06-24T14:58:37 |
|
mitmproxy/mitmproxy | 4,681 | mitmproxy__mitmproxy-4681 | [
"4678"
] | 18ca5a63699d9376d1711ab0ecdb153106416d64 | 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
@@ -1,7 +1,7 @@
import struct
import time
from dataclasses import dataclass
-from typing import Iterator, Optional, Tuple
+from typing import Iterator, Literal, Optional, Tuple
from OpenSSL import SSL
from mitmproxy import certs, connection
@@ -22,10 +22,10 @@ def is_tls_handshake_record(d: bytes) -> bool:
# TLS 1.3 mandates legacy_record_version to be 0x0301.
# http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html#client-hello
return (
- len(d) >= 3 and
- d[0] == 0x16 and
- d[1] == 0x03 and
- 0x0 <= d[2] <= 0x03
+ len(d) >= 3 and
+ d[0] == 0x16 and
+ d[1] == 0x03 and
+ 0x0 <= d[2] <= 0x03
)
@@ -161,6 +161,8 @@ def __repr__(self):
def start_tls(self) -> layer.CommandGenerator[None]:
assert not self.tls
+ if not self.conn.connected:
+ return
tls_start = TlsStartData(self.conn, self.context)
if tls_start.conn == tls_start.context.client:
@@ -379,6 +381,8 @@ def receive_handshake_data(self, data: bytes) -> layer.CommandGenerator[Tuple[bo
f"Trying to establish TLS with client anyway.")
yield from self.start_tls()
+ if not self.conn.connected:
+ return False, "connection closed early"
ret = yield from super().receive_handshake_data(bytes(self.recv_buffer))
self.recv_buffer.clear()
@@ -399,13 +403,23 @@ def on_handshake_error(self, err: str) -> layer.CommandGenerator[None]:
dest = self.conn.sni
else:
dest = human.format_address(self.context.server.address)
+ level: Literal["warn", "info"] = "warn"
if err.startswith("Cannot parse ClientHello"):
pass
elif "unknown ca" in err or "bad certificate" in err:
err = f"The client does not trust the proxy's certificate for {dest} ({err})"
+ elif err == "connection closed":
+ err = (
+ f"The client disconnected during the handshake. If this happens consistently for {dest}, "
+ f"this may indicate that the client does not trust the proxy's certificate."
+ )
+ level = "info"
+ elif err == "connection closed early":
+ pass
else:
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")
+ if err != "connection closed early":
+ yield commands.Log(f"Client TLS handshake failed. {err}", level=level)
yield from super().on_handshake_error(err)
self.event_to_child = self.errored # type: ignore
| 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
@@ -520,20 +520,45 @@ def test_mitmproxy_ca_is_untrusted(self, tctx: context.Context):
)
assert not tctx.client.tls_established
- def test_mitmproxy_ca_is_untrusted_immediate_disconnect(self, tctx: context.Context):
- """Test the scenario where the client doesn't trust the mitmproxy CA."""
+ @pytest.mark.parametrize("close_at", ["tls_clienthello", "tls_start_client", "handshake"])
+ def test_immediate_disconnect(self, tctx: context.Context, close_at):
+ """Test the scenario where the client is disconnecting during the handshake.
+ This may happen because they are not interested in the connection anymore, or because they do not like
+ the proxy certificate."""
playbook, client_layer, tssl_client = make_client_tls_layer(tctx, sni=b"wrong.host.mitmproxy.org")
+ playbook.logs = True
- assert (
+ playbook >> events.DataReceived(tctx.client, tssl_client.bio_read())
+ playbook << tls.TlsClienthelloHook(tutils.Placeholder())
+
+ if close_at == "tls_clienthello":
+ assert (
playbook
- >> events.DataReceived(tctx.client, tssl_client.bio_read())
- << tls.TlsClienthelloHook(tutils.Placeholder())
- >> tutils.reply()
- << tls.TlsStartClientHook(tutils.Placeholder())
- >> reply_tls_start_client()
- << commands.SendData(tctx.client, tutils.Placeholder())
>> events.ConnectionClosed(tctx.client)
- << commands.Log("Client TLS handshake failed. The client may not trust the proxy's certificate "
- "for wrong.host.mitmproxy.org (connection closed)", "warn")
+ >> tutils.reply(to=-2)
<< commands.CloseConnection(tctx.client)
+ )
+ return
+
+ playbook >> tutils.reply()
+ playbook << tls.TlsStartClientHook(tutils.Placeholder())
+
+ if close_at == "tls_start_client":
+ assert (
+ playbook
+ >> events.ConnectionClosed(tctx.client)
+ >> reply_tls_start_client(to=-2)
+ << commands.CloseConnection(tctx.client)
+ )
+ return
+
+ assert (
+ playbook
+ >> reply_tls_start_client()
+ << commands.SendData(tctx.client, tutils.Placeholder())
+ >> events.ConnectionClosed(tctx.client)
+ << commands.Log("Client TLS handshake failed. The client disconnected during the handshake. "
+ "If this happens consistently for wrong.host.mitmproxy.org, this may indicate that the "
+ "client does not trust the proxy's certificate.", "info")
+ << commands.CloseConnection(tctx.client)
)
| Client TLS handshake failed. The client may not trust the proxy's certificate for static-assets.highwebmedia.com (connection closed)
#### Problem Description
v6 does not log these errors. The thing is that directly connecting to these hosts works too without error. And it seems like everything is working, so what's going on here? Does it actually fail?
```
Client TLS handshake failed. The client may not trust the proxy's certificate for static-assets.highwebmedia.com (connection closed)
Client TLS handshake failed. The client may not trust the proxy's certificate for roomimg.stream.highwebmedia.com (connection closed)
```
#### Steps to reproduce the behavior:
1. `mitmproxy`
2. Open Chromium via proxy
3. Visit https://chaturbate.com (obligatory https://hackerone.com/chaturbate)
You'll instantly see the error.
Here's `-set proxy_debug -vvv` for v6 and v7
[v6.log](https://github.com/mitmproxy/mitmproxy/files/6814791/v6.log)
[v7.log](https://github.com/mitmproxy/mitmproxy/files/6814792/v7.log)
#### System Information
main, does not happen on 6.0.2
| I might look into this some more later, I'll assign the issue to myself if I do so.
Could this _somehow_ be related to me using the same `.config/mitmproxy` certs and switching between v6 and v7? The ca was generated with v6 I guess.
Thanks, this is useful. Tracking this down:
1. I first grep the log for "The client may not trust the proxy's certificate" to see that the connection with source port 58954 is affected.
2. Next, I run `test/helper_tools/loggrep.py 58954 v7.log` to only see events relating to that connection.
3. Refine with `test/helper_tools/loggrep.py 58954 v7.log | rg "SendData|ConnectionClosed" -C 1000` to highlight specific keywords.
Using that approach we see that the client unexpectedly disconnects while mitmproxy is negotiating TLS with the server. The error by itself is not wrong, but in this particular setting we can be more precise: We haven't presented a cert yet, so we can be sure that it's not because the CA is untrusted. The general problem is that some TLS clients just hang up after being presented with an untrusted cert, so we can't entirely avoid false-positives here. | 2021-07-15T09:56:39 |
mitmproxy/mitmproxy | 4,692 | mitmproxy__mitmproxy-4692 | [
"4689"
] | c718d4f7b0fb98bcab90bc09608f899c27790237 | diff --git a/mitmproxy/addons/tlsconfig.py b/mitmproxy/addons/tlsconfig.py
--- a/mitmproxy/addons/tlsconfig.py
+++ b/mitmproxy/addons/tlsconfig.py
@@ -8,10 +8,11 @@
from mitmproxy.net import tls as net_tls
from mitmproxy.options import CONF_BASENAME
from mitmproxy.proxy import context
-from mitmproxy.proxy.layers import tls
+from mitmproxy.proxy.layers import tls, modes
# We manually need to specify this, otherwise OpenSSL may select a non-HTTP2 cipher by default.
# https://ssl-config.mozilla.org/#config=old
+
DEFAULT_CIPHERS = (
'ECDHE-ECDSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES256-GCM-SHA384',
'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-ECDSA-CHACHA20-POLY1305', 'ECDHE-RSA-CHACHA20-POLY1305',
@@ -118,13 +119,8 @@ def tls_clienthello(self, tls_clienthello: tls.ClientHelloData):
)
)
- def tls_start_client(self, tls_start: tls.TlsStartData):
- self.create_client_proxy_ssl_conn(tls_start)
-
- def tls_start_server(self, tls_start: tls.TlsStartData):
- self.create_proxy_server_ssl_conn(tls_start)
-
- def create_client_proxy_ssl_conn(self, tls_start: tls.TlsStartData) -> None:
+ def tls_start_client(self, tls_start: tls.TlsStartData) -> None:
+ """Establish TLS between client and proxy."""
client: connection.Client = tls_start.context.client
server: connection.Server = tls_start.context.server
@@ -154,14 +150,24 @@ def create_client_proxy_ssl_conn(self, tls_start: tls.TlsStartData) -> None:
dhparams=self.certstore.dhparams,
)
tls_start.ssl_conn = SSL.Connection(ssl_ctx)
+
+ # Force HTTP/1 for secure web proxies, we currently don't support CONNECT over HTTP/2.
+ # There is a proof-of-concept branch at https://github.com/mhils/mitmproxy/tree/http2-proxy,
+ # but the complexity outweighs the benefits for now.
+ if len(tls_start.context.layers) == 2 and isinstance(tls_start.context.layers[0], modes.HttpProxy):
+ client_alpn: Optional[bytes] = b"http/1.1"
+ else:
+ client_alpn = client.alpn
+
tls_start.ssl_conn.set_app_data(AppData(
- client_alpn=client.alpn,
+ client_alpn=client_alpn,
server_alpn=server.alpn,
http2=ctx.options.http2,
))
tls_start.ssl_conn.set_accept_state()
- def create_proxy_server_ssl_conn(self, tls_start: tls.TlsStartData) -> None:
+ def tls_start_server(self, tls_start: tls.TlsStartData) -> None:
+ """Establish TLS between proxy and server."""
client: connection.Client = tls_start.context.client
server: connection.Server = tls_start.context.server
assert server.address
@@ -296,9 +302,10 @@ def get_cert(self, conn_context: context.Context) -> certs.CertStoreEntry:
elif conn_context.server.address:
altnames.append(conn_context.server.address[0])
- # As a last resort, add *something* so that we have a certificate to serve.
+ # As a last resort, add our local IP address. This may be necessary for HTTPS Proxies which are addressed
+ # via IP. Here we neither have an upstream cert, nor can an IP be included in the server name indication.
if not altnames:
- altnames.append("mitmproxy")
+ altnames.append(conn_context.client.sockname[0])
# only keep first occurrence of each hostname
altnames = list(dict.fromkeys(altnames))
diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py
--- a/mitmproxy/certs.py
+++ b/mitmproxy/certs.py
@@ -49,6 +49,9 @@ def __init__(self, cert: x509.Certificate):
def __eq__(self, other):
return self.fingerprint() == other.fingerprint()
+ def __repr__(self):
+ return f"<Cert(cn={self.cn!r}, altnames={self.altnames!r})>"
+
@classmethod
def from_state(cls, state):
return cls.from_pem(state)
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
@@ -346,6 +346,23 @@ class ClientTLSLayer(_TLSLayer):
client_hello_parsed: bool = False
def __init__(self, context: context.Context):
+ if context.client.tls:
+ # In the case of TLS-over-TLS, we already have client TLS. As the outer TLS connection between client
+ # and proxy isn't that interesting to us, we just unset the attributes here and keep the inner TLS
+ # session's attributes.
+ # Alternatively we could create a new Client instance,
+ # but for now we keep it simple. There is a proof-of-concept at
+ # https://github.com/mitmproxy/mitmproxy/commit/9b6e2a716888b7787514733b76a5936afa485352.
+ context.client.alpn = None
+ context.client.cipher = None
+ context.client.sni = None
+ context.client.timestamp_tls_setup = None
+ context.client.tls_version = None
+ context.client.certificate_list = []
+ context.client.mitmcert = None
+ context.client.alpn_offers = []
+ context.client.cipher_list = []
+
super().__init__(context, context.client)
self.server_tls_available = isinstance(self.context.layers[-2], ServerTLSLayer)
self.recv_buffer = bytearray()
| diff --git a/test/mitmproxy/addons/test_tlsconfig.py b/test/mitmproxy/addons/test_tlsconfig.py
--- a/test/mitmproxy/addons/test_tlsconfig.py
+++ b/test/mitmproxy/addons/test_tlsconfig.py
@@ -9,7 +9,7 @@
from mitmproxy import certs, connection
from mitmproxy.addons import tlsconfig
from mitmproxy.proxy import context
-from mitmproxy.proxy.layers import tls
+from mitmproxy.proxy.layers import modes, tls
from mitmproxy.test import taddons
from test.mitmproxy.proxy.layers import test_tls
@@ -66,9 +66,10 @@ def test_get_cert(self, tdata):
ctx = context.Context(connection.Client(("client", 1234), ("127.0.0.1", 8080), 1605699329), tctx.options)
- # Edge case first: We don't have _any_ idea about the server, so we just return "mitmproxy" as subject.
+ # Edge case first: We don't have _any_ idea about the server nor is there a SNI,
+ # so we just return our local IP as subject.
entry = ta.get_cert(ctx)
- assert entry.cert.cn == "mitmproxy"
+ assert entry.cert.cn == "127.0.0.1"
# Here we have an existing server connection...
ctx.server.address = ("server-address.example", 443)
@@ -114,7 +115,7 @@ def do_handshake(
return True
- def test_create_client_proxy_ssl_conn(self, tdata):
+ def test_tls_start_client(self, tdata):
ta = tlsconfig.TlsConfig()
with taddons.context(ta) as tctx:
ta.configure(["confdir"])
@@ -132,7 +133,7 @@ def test_create_client_proxy_ssl_conn(self, tdata):
assert self.do_handshake(tssl_client, tssl_server)
assert tssl_client.obj.getpeercert()["subjectAltName"] == (("DNS", "example.mitmproxy.org"),)
- def test_create_proxy_server_ssl_conn_verify_failed(self):
+ def test_tls_start_server_verify_failed(self):
ta = tlsconfig.TlsConfig()
with taddons.context(ta) as tctx:
ctx = context.Context(connection.Client(("client", 1234), ("127.0.0.1", 8080), 1605699329), tctx.options)
@@ -147,7 +148,7 @@ def test_create_proxy_server_ssl_conn_verify_failed(self):
with pytest.raises(SSL.Error, match="certificate verify failed"):
assert self.do_handshake(tssl_client, tssl_server)
- def test_create_proxy_server_ssl_conn_verify_ok(self, tdata):
+ def test_tls_start_server_verify_ok(self, tdata):
ta = tlsconfig.TlsConfig()
with taddons.context(ta) as tctx:
ctx = context.Context(connection.Client(("client", 1234), ("127.0.0.1", 8080), 1605699329), tctx.options)
@@ -161,7 +162,7 @@ def test_create_proxy_server_ssl_conn_verify_ok(self, tdata):
tssl_server = test_tls.SSLTest(server_side=True)
assert self.do_handshake(tssl_client, tssl_server)
- def test_create_proxy_server_ssl_conn_insecure(self):
+ def test_tls_start_server_insecure(self):
ta = tlsconfig.TlsConfig()
with taddons.context(ta) as tctx:
ctx = context.Context(connection.Client(("client", 1234), ("127.0.0.1", 8080), 1605699329), tctx.options)
@@ -203,6 +204,24 @@ def assert_alpn(http2, client_offers, expected):
# see comment in tlsconfig.py
assert_alpn(True, [], [])
+ def test_no_h2_proxy(self, tdata):
+ """Do not negotiate h2 on the client<->proxy connection in secure web proxy mode,
+ https://github.com/mitmproxy/mitmproxy/issues/4689"""
+
+ ta = tlsconfig.TlsConfig()
+ with taddons.context(ta) as tctx:
+ tctx.configure(ta, certs=[tdata.path("mitmproxy/net/data/verificationcerts/trusted-leaf.pem")])
+
+ ctx = context.Context(connection.Client(("client", 1234), ("127.0.0.1", 8080), 1605699329), tctx.options)
+ # mock up something that looks like a secure web proxy.
+ ctx.layers = [
+ modes.HttpProxy(ctx),
+ 123
+ ]
+ tls_start = tls.TlsStartData(ctx.client, context=ctx)
+ ta.tls_start_client(tls_start)
+ assert tls_start.ssl_conn.get_app_data()["client_alpn"] == b"http/1.1"
+
@pytest.mark.parametrize(
"client_certs",
[
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
@@ -180,6 +180,7 @@ def test_simple(self, tdata):
assert c2.issuer
assert c2.to_pem()
assert c2.has_expired() is not None
+ assert repr(c2) == "<Cert(cn='www.inode.co.nz', altnames=['www.inode.co.nz', 'inode.co.nz'])>"
assert c1 != c2
| TLS-over-TLS does not play nice with Firefox
#### Problem Description
Mitmproxy's new HTTPS proxy functionality does not seem to work well with Firefox.
1. I am getting certificate errors in Firefox when specifying https://127.0.0.1 as the proxy address (mitmproxy: `The client does not trust the proxy's certificate for <no address> (sslv3 alert bad certificate)`)
2. When switching to https://localhost, page load hangs infinitely and mitmproxy complains about ` Invalid HTTP/2 request headers: Required pseudo header is missing: b':scheme'`.
The workaround that works for me is to specify `https://localhost:8080` as the proxy and run mitmproxy with `--no-http2`, or to run mitmproxy as a regular HTTP (not HTTPS) proxy, which of course still works with TLS sites.
#### System Information
```
Mitmproxy: 7.0.0
Python: 3.9.4
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Linux-4.4.0-19041-Microsoft-x86_64-with-glibc2.31
```
| 2021-07-20T13:32:15 |
|
mitmproxy/mitmproxy | 4,693 | mitmproxy__mitmproxy-4693 | [
"4614"
] | c718d4f7b0fb98bcab90bc09608f899c27790237 | diff --git a/mitmproxy/tools/console/keybindings.py b/mitmproxy/tools/console/keybindings.py
--- a/mitmproxy/tools/console/keybindings.py
+++ b/mitmproxy/tools/console/keybindings.py
@@ -66,6 +66,7 @@ def set_focus(self, index):
self.index = index
self.focus_obj = self._get(self.index)
keybinding_focus_change.send(binding.help or "")
+ self._modified()
def get_next(self, pos):
if pos >= len(self.bindings) - 1:
@@ -79,6 +80,12 @@ def get_prev(self, pos):
return None, None
return self._get(pos), pos
+ def positions(self, reverse=False):
+ if reverse:
+ return reversed(range(len(self.bindings)))
+ else:
+ return range(len(self.bindings))
+
class KeyList(urwid.ListBox):
def __init__(self, master):
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
@@ -142,6 +142,7 @@ def set_focus(self, index):
self.index = index
self.focus_obj = self._get(self.index, self.editing)
option_focus_change.send(opt.help)
+ self._modified()
def get_next(self, pos):
if pos >= len(self.opts) - 1:
@@ -155,6 +156,12 @@ def get_prev(self, pos):
return None, None
return self._get(pos, False), pos
+ def positions(self, reverse=False):
+ if reverse:
+ return reversed(range(len(self.opts)))
+ else:
+ return range(len(self.opts))
+
class OptionsList(urwid.ListBox):
def __init__(self, master):
| diff --git a/test/mitmproxy/tools/console/test_integration.py b/test/mitmproxy/tools/console/test_integration.py
--- a/test/mitmproxy/tools/console/test_integration.py
+++ b/test/mitmproxy/tools/console/test_integration.py
@@ -43,3 +43,11 @@ def test_integration(tdata, console):
console.type(f":view.flows.load {tdata.path('mitmproxy/data/dumpfile-7.mitm')}<enter>")
console.type("<enter><tab><tab>")
console.type("<space><tab><tab>") # view second flow
+
+
+def test_options_home_end(console):
+ console.type("O<home><end>")
+
+
+def test_keybindings_home_end(console):
+ console.type("K<home><end>")
\ No newline at end of file
| Options and Keybinding screen: home and end crash mitmproxy
#### Problem Description
In both the Options and Keybindings views pressing home or end will crash mitmproxy.
#### Steps to reproduce the behavior:
1. `mitmproxy`, K, Home
or
1. `mitmproxy`, O, Home
#### System Information
```
$ mitmproxy --version
Mitmproxy: 7.0.0.dev (+449, commit 4f60e52)
Python: 3.9.2
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Linux-5.10.0-kali3-amd64-x86_64-with-glibc2.31
```
```
Mitmproxy: 7.0.0.dev (+449, commit 4f60e52)
Python: 3.9.4
OpenSSL: OpenSSL 1.1.1i 8 Dec 2020
Platform: macOS-10.15.7-x86_64-i386-64bit
```
#### Patch
Not really sure this is perfect but this fixed it locally. I can send this as a PR if it is appropriate.
```diff
diff --git a/mitmproxy/tools/console/keybindings.py b/mitmproxy/tools/console/keybindings.py
index 312c19f94..6d08d135e 100644
--- a/mitmproxy/tools/console/keybindings.py
+++ b/mitmproxy/tools/console/keybindings.py
@@ -66,6 +66,8 @@ class KeyListWalker(urwid.ListWalker):
self.index = index
self.focus_obj = self._get(self.index)
keybinding_focus_change.send(binding.help or "")
+ self._modified()
+
def get_next(self, pos):
if pos >= len(self.bindings) - 1:
@@ -79,6 +81,12 @@ class KeyListWalker(urwid.ListWalker):
return None, None
return self._get(pos), pos
+ def positions(self, reverse=False):
+ if reverse:
+ return reversed(range(len(self.bindings)))
+ else:
+ return range(len(self.bindings))
+
class KeyList(urwid.ListBox):
def __init__(self, master):
diff --git a/mitmproxy/tools/console/options.py b/mitmproxy/tools/console/options.py
index 5e5ef2a68..0c780f638 100644
--- a/mitmproxy/tools/console/options.py
+++ b/mitmproxy/tools/console/options.py
@@ -142,6 +142,8 @@ class OptionListWalker(urwid.ListWalker):
self.index = index
self.focus_obj = self._get(self.index, self.editing)
option_focus_change.send(opt.help)
+ self._modified()
+
def get_next(self, pos):
if pos >= len(self.opts) - 1:
@@ -155,6 +157,11 @@ class OptionListWalker(urwid.ListWalker):
return None, None
return self._get(pos, False), pos
+ def positions(self, reverse=False):
+ if reverse:
+ return reversed(range(len(self.opts)))
+ else:
+ return range(len(self.opts))
class OptionsList(urwid.ListBox):
def __init__(self, master):
```
| 2021-07-20T14:59:18 |
|
mitmproxy/mitmproxy | 4,716 | mitmproxy__mitmproxy-4716 | [
"4705"
] | 7da9e52ff3ae1a84799fc1c53e70139ba45b5907 | diff --git a/mitmproxy/io/io.py b/mitmproxy/io/io.py
--- a/mitmproxy/io/io.py
+++ b/mitmproxy/io/io.py
@@ -1,5 +1,5 @@
import os
-from typing import Any, Dict, Iterable, Type, Union, cast # noqa
+from typing import Any, Dict, IO, Iterable, Type, Union, cast
from mitmproxy import exceptions
from mitmproxy import flow
@@ -25,8 +25,8 @@ def add(self, flow):
class FlowReader:
- def __init__(self, fo):
- self.fo = fo
+ def __init__(self, fo: IO[bytes]):
+ self.fo: IO[bytes] = fo
def stream(self) -> Iterable[flow.Flow]:
"""
@@ -46,7 +46,7 @@ def stream(self) -> Iterable[flow.Flow]:
if mdata["type"] not in FLOW_TYPES:
raise exceptions.FlowReadException("Unknown flow type: {}".format(mdata["type"]))
yield FLOW_TYPES[mdata["type"]].from_state(mdata)
- except ValueError as e:
+ except (ValueError, TypeError) as e:
if str(e) == "not a tnetstring: empty file":
return # Error is due to EOF
raise exceptions.FlowReadException("Invalid data format.")
diff --git a/mitmproxy/io/tnetstring.py b/mitmproxy/io/tnetstring.py
--- a/mitmproxy/io/tnetstring.py
+++ b/mitmproxy/io/tnetstring.py
@@ -58,7 +58,7 @@ def dumps(value: TSerializable) -> bytes:
return b''.join(q)
-def dump(value: TSerializable, file_handle: typing.BinaryIO) -> None:
+def dump(value: TSerializable, file_handle: typing.IO[bytes]) -> None:
"""
This function dumps a python object as a tnetstring and
writes it to the given file.
@@ -156,7 +156,7 @@ def loads(string: bytes) -> TSerializable:
return pop(string)[0]
-def load(file_handle: typing.BinaryIO) -> TSerializable:
+def load(file_handle: typing.IO[bytes]) -> TSerializable:
"""load(file) -> object
This function reads a tnetstring from a file and parses it into a
| diff --git a/test/mitmproxy/io/test_io.py b/test/mitmproxy/io/test_io.py
--- a/test/mitmproxy/io/test_io.py
+++ b/test/mitmproxy/io/test_io.py
@@ -1 +1,35 @@
-# TODO: write tests
+import io
+
+import pytest
+from hypothesis import example, given
+from hypothesis.strategies import binary
+
+from mitmproxy import exceptions, version
+from mitmproxy.io import FlowReader, tnetstring
+
+
+class TestFlowReader:
+ @given(binary())
+ @example(b'51:11:12345678901#4:this,8:true!0:~,4:true!0:]4:\\x00,~}')
+ def test_fuzz(self, data):
+ f = io.BytesIO(data)
+ reader = FlowReader(f)
+ try:
+ for _ in reader.stream():
+ pass
+ except exceptions.FlowReadException:
+ pass # should never raise anything else.
+
+ def test_empty(self):
+ assert list(FlowReader(io.BytesIO(b"")).stream()) == []
+
+ def test_unknown_type(self):
+ with pytest.raises(exceptions.FlowReadException, match="Unknown flow type"):
+ weird_flow = tnetstring.dumps({"type": "unknown", "version": version.FLOW_FORMAT_VERSION})
+ for _ in FlowReader(io.BytesIO(weird_flow)).stream():
+ pass
+
+ def test_cannot_migrate(self):
+ with pytest.raises(exceptions.FlowReadException, match="cannot read files with flow format version 0"):
+ for _ in FlowReader(io.BytesIO(b"14:7:version;1:0#}")).stream():
+ pass
| Doesn't properly check invalid input in tnetstring.parse
#### Problem Description
In the [condiction branch](https://github.com/mitmproxy/mitmproxy/blob/0ca458fd6475ee48728147f3b529467a75e912a4/mitmproxy/io/tnetstring.py#L218) ```data_type == ord(b'}')```of tnetstring.parse(), it doesn't properly check invalid data in the parse loop.
#### Steps to reproduce the behavior:
```
from mitmproxy.io import tnetstring
t = b'51:11:12345678901#4:this,8:true!0:~,4:true!0:]4:\\x00,~}'
tnetstring.loads(t)
TypeError: unhashable type: 'list'
```

#### System Information
Mitmproxy: 7.0.0
Python: 3.8.2
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Linux-5.4.0-kali3-amd64-x86_64-with-glibc2.29
| I'm not sure if I understand what's the problem here. Is there any way how you can trigger this issue from mitmproxy? Lists aren't supported as dictionary keys in our tnetstring implementation.
It's somewhat expected that tnetstring.loads borks on invalid input, but I don't understand where that is a Denial-of-Service issue.
> I'm not sure if I understand what's the problem here. Is there any way how you can trigger this issue from mitmproxy? Lists aren't supported as dictionary keys in our tnetstring implementation.
>
> It's somewhat expected that tnetstring.loads borks on invalid input, but I don't understand where that is a Denial-of-Service issue.
sorry for the description. It just because I found this issue will make a crash.

| 2021-08-01T12:59:15 |
mitmproxy/mitmproxy | 4,719 | mitmproxy__mitmproxy-4719 | [
"4701"
] | 9d02eb91c47a4eadebde60d4ace432f27e421b95 | diff --git a/mitmproxy/proxy/layers/websocket.py b/mitmproxy/proxy/layers/websocket.py
--- a/mitmproxy/proxy/layers/websocket.py
+++ b/mitmproxy/proxy/layers/websocket.py
@@ -65,7 +65,7 @@ class WebsocketConnection(wsproto.Connection):
def __init__(self, *args, conn: connection.Connection, **kwargs):
super(WebsocketConnection, self).__init__(*args, **kwargs)
self.conn = conn
- self.frame_buf = []
+ self.frame_buf = [b""]
def send2(self, event: wsproto.events.Event) -> commands.SendData:
data = self.send(event)
@@ -155,10 +155,10 @@ def relay_messages(self, event: events.Event) -> layer.CommandGenerator[None]:
is_text = isinstance(ws_event.data, str)
if is_text:
typ = Opcode.TEXT
- src_ws.frame_buf.append(ws_event.data.encode())
+ src_ws.frame_buf[-1] += ws_event.data.encode()
else:
typ = Opcode.BINARY
- src_ws.frame_buf.append(ws_event.data)
+ src_ws.frame_buf[-1] += ws_event.data
if ws_event.message_finished:
content = b"".join(src_ws.frame_buf)
@@ -174,6 +174,9 @@ def relay_messages(self, event: events.Event) -> layer.CommandGenerator[None]:
for msg in fragmentizer(message.content):
yield dst_ws.send2(msg)
+ elif ws_event.frame_finished:
+ src_ws.frame_buf.append(b"")
+
elif isinstance(ws_event, (wsproto.events.Ping, wsproto.events.Pong)):
yield commands.Log(
f"Received WebSocket {ws_event.__class__.__name__.lower()} from {from_str} "
@@ -209,8 +212,11 @@ class Fragmentizer:
Practice:
Some WebSocket servers reject large payload sizes.
+ Other WebSocket servers reject CONTINUATION frames.
As a workaround, we either retain the original chunking or, if the payload has been modified, use ~4kB chunks.
+ If one deals with web servers that do not support CONTINUATION frames, addons need to monkeypatch FRAGMENT_SIZE
+ if they need to modify the message.
"""
# A bit less than 4kb to accommodate for headers.
FRAGMENT_SIZE = 4000
| diff --git a/test/mitmproxy/proxy/layers/test_websocket.py b/test/mitmproxy/proxy/layers/test_websocket.py
--- a/test/mitmproxy/proxy/layers/test_websocket.py
+++ b/test/mitmproxy/proxy/layers/test_websocket.py
@@ -193,6 +193,26 @@ def test_fragmented(ws_testdata):
assert flow.websocket.messages[-1].content == b"foobar"
+def test_unfragmented(ws_testdata):
+ tctx, playbook, flow = ws_testdata
+ assert (
+ playbook
+ << websocket.WebsocketStartHook(flow)
+ >> reply()
+ >> DataReceived(tctx.server, b"\x81\x06foo")
+ )
+ # This already triggers wsproto to emit a wsproto.events.Message, see
+ # https://github.com/mitmproxy/mitmproxy/issues/4701
+ assert(
+ playbook
+ >> DataReceived(tctx.server, b"bar")
+ << websocket.WebsocketMessageHook(flow)
+ >> reply()
+ << SendData(tctx.client, b"\x81\x06foobar")
+ )
+ assert flow.websocket.messages[-1].content == b"foobar"
+
+
def test_protocol_error(ws_testdata):
tctx, playbook, flow = ws_testdata
assert (
| Unfragmented WebSocket messages getting fragmented
https://github.com/mitmproxy/mitmproxy/blob/e270399a3eba7b3212bf7325beaa50e159a7ca0a/mitmproxy/proxy/layers/websocket.py#L153-L175
While handling WebSocket events, mitmproxy doesn't distinguish between `message_finished` and `frame_finished` ([Message class](https://python-hyper.org/projects/wsproto/en/stable/api.html#wsproto.events.Message)) which in my case led to continuation frames being sent while there were none in the initial WebSocket message.
This is because the wsproto API doesn't always emit complete frames (I guess this is caused by the TCP fragmentation?), they could be chunked while the original WebSocket message has no fragmentation and I think even WebSocket messages using fragmentation with large continuation frames could be emitted as chunks themselves?
To avoid this behavior each `frame_buf` entry must be a complete frame, here is my fix suggestion:
```python
for ws_event in src_ws.events():
if isinstance(ws_event, wsproto.events.Message):
is_text = isinstance(ws_event.data, str)
# Add the data variable to avoid multiple conditions
if is_text:
typ = Opcode.TEXT
data = ws_event.data.encode()
else:
typ = Opcode.BINARY
data = ws_event.data
# Make each frame one entry to frame_buf, append if empty to avoid IndexError
if src_ws.frame_buf:
src_ws.frame_buf[-1] += data
else:
src_ws.frame_buf.append(data)
if ws_event.message_finished:
content = b"".join(src_ws.frame_buf)
fragmentizer = Fragmentizer(src_ws.frame_buf, is_text)
src_ws.frame_buf.clear()
message = websocket.WebSocketMessage(typ, from_client, content)
self.flow.websocket.messages.append(message)
yield WebsocketMessageHook(self.flow)
if not message.dropped:
for msg in fragmentizer(message.content):
yield dst_ws.send2(msg)
# Initialize next frame entry
elif ws_event.frame_finished:
src_ws.frame_buf.append(b"")
```
It works for me but I didn't test it with in an environment using WebSocket continuation frames. Also this only works for unmodified WebSocket messages, injected or modified messages are still concerned by the issue because the `Fragmentizer` class compares the lengths so they will always fall into the else condition (unless you made the modified message keep its original length):
https://github.com/mitmproxy/mitmproxy/blob/e270399a3eba7b3212bf7325beaa50e159a7ca0a/mitmproxy/proxy/layers/websocket.py#L229-L243
For my use case I didn't make a proper fix for this, I just made the first condition always true, maybe a boolean variable can be added to the `WebSocketMessage` and `Fragmentizer` classes or something like that?
| 2021-08-02T12:19:49 |
|
mitmproxy/mitmproxy | 4,721 | mitmproxy__mitmproxy-4721 | [
"4713"
] | b57bc68c515f9092832e3e22a929049557380a0e | diff --git a/mitmproxy/addons/tlsconfig.py b/mitmproxy/addons/tlsconfig.py
--- a/mitmproxy/addons/tlsconfig.py
+++ b/mitmproxy/addons/tlsconfig.py
@@ -290,11 +290,18 @@ def get_cert(self, conn_context: context.Context) -> certs.CertStoreEntry:
# Use upstream certificate if available.
if conn_context.server.certificate_list:
upstream_cert = conn_context.server.certificate_list[0]
- if upstream_cert.cn:
- altnames.append(upstream_cert.cn)
+ try:
+ # a bit clunky: access to .cn can fail, see https://github.com/mitmproxy/mitmproxy/issues/4713
+ if upstream_cert.cn:
+ altnames.append(upstream_cert.cn)
+ except ValueError:
+ pass
altnames.extend(upstream_cert.altnames)
- if upstream_cert.organization:
- organization = upstream_cert.organization
+ try:
+ if upstream_cert.organization:
+ organization = upstream_cert.organization
+ except ValueError:
+ pass
# Add SNI. If not available, try the server address as well.
if conn_context.client.sni:
| diff --git a/test/mitmproxy/addons/test_tlsconfig.py b/test/mitmproxy/addons/test_tlsconfig.py
--- a/test/mitmproxy/addons/test_tlsconfig.py
+++ b/test/mitmproxy/addons/test_tlsconfig.py
@@ -84,6 +84,10 @@ def test_get_cert(self, tdata):
entry = ta.get_cert(ctx)
assert entry.cert.altnames == ["example.mitmproxy.org", "sni.example"]
+ with open(tdata.path("mitmproxy/data/invalid-subject.pem"), "rb") as f:
+ ctx.server.certificate_list = [certs.Cert.from_pem(f.read())]
+ assert ta.get_cert(ctx) # does not raise
+
def test_tls_clienthello(self):
# only really testing for coverage here, there's no point in mirroring the individual conditions
ta = tlsconfig.TlsConfig()
diff --git a/test/mitmproxy/data/invalid-subject.pem b/test/mitmproxy/data/invalid-subject.pem
new file mode 100644
--- /dev/null
+++ b/test/mitmproxy/data/invalid-subject.pem
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICzDCCAomgAwIBAgIEZu2lSDALBgcqhkjOOAQDBQAwNjEQMA4GA1UEBhMHc2lh
+dmFzaDEQMA4GA1UEChMHc2lhdmFzaDEQMA4GA1UEAxMHc2lhdmFzaDAgFw0xNjAx
+MjUwNzI1MzBaGA8yMDU0MDUyNTA3MjUzMFowNjEQMA4GA1UEBhMHc2lhdmFzaDEQ
+MA4GA1UEChMHc2lhdmFzaDEQMA4GA1UEAxMHc2lhdmFzaDCCAbgwggEsBgcqhkjO
+OAQBMIIBHwKBgQD9f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR
++1k9jVj6v8X1ujD2y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb
++DtX58aophUPBPuD9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdg
+UI8VIwvMspK5gqLrhAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlX
+TAs9B4JnUVlXjrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCj
+rh4rs6Z1kW6jfwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQB
+TDv+z0kqA4GFAAKBgQDptGpQCqvLt7Quk0d9ufisfIGerdOS9Pot18EJc8OZ0A1F
+eWBSv7N2VnpRjP4UMqD4ReS+dap2RiM1v3+EtsY0u2yIS2ri57bxzHjDvm+YtlmA
+gyxA2do9KwR8upiyTId7Ks55CLCvVv1iNn3zVeARoEgsm4dRw3Oo0TEHbNAUIaMh
+MB8wHQYDVR0OBBYEFO6sMuXwh4G7by85KBSVGzKIaK5MMAsGByqGSM44BAMFAAMw
+ADAtAhUAkgnrEulmqvrigWIOfal0N3TXhGMCFEvzapY0lnykdjm7wQcSVxsDbhPV
+-----END CERTIFICATE-----
| MITMproxy crashes when using upstream proxy with -k
#### Problem Description
As the title says, I'm using mitmproxy with an upstream proxy (burp) and the
`-k` flag, and it crashes
#### Steps to reproduce the behavior:
1. Setup burp listening on 8081
2. Open mitmproxy with `mitmproxy -k --mode "upstream:http://127.0.0.1:8081"`
3. Try and send a request, e.g. `curl https://jonathanh.co.uk -k` through the proxies
#### System Information
Paste the output of "mitmproxy --version" here.
```
Mitmproxy: 7.0.0
Python: 3.9.6
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Linux-5.12.15-zen1-1-zen-x86_64-with-glibc2.33
```
### Event Log
The event log contains the following:
```
info: Proxy server listening at http://*:8080
info: 127.0.0.1:55706: client connect
info: 127.0.0.1:55706: server connect 127.0.0.1:8081
error: Addon error: Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/mitmproxy/addons/tlsconfig.py", line 122, in tls_start_client
self.create_client_proxy_ssl_conn(tls_start)
File "/usr/lib/python3.9/site-packages/mitmproxy/addons/tlsconfig.py", line 131, in create_client_proxy_ssl_conn
entry = self.get_cert(tls_start.context)
File "/usr/lib/python3.9/site-packages/mitmproxy/addons/tlsconfig.py", line 287, in get_cert
if upstream_cert.cn:
File "/usr/lib/python3.9/site-packages/mitmproxy/certs.py", line 117, in cn
attrs = self._cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)
File "/usr/lib/python3.9/site-packages/cryptography/hazmat/backends/openssl/x509.py", line 110, in subject
return _decode_x509_name(self._backend, subject)
File "/usr/lib/python3.9/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py", line 63, in _decode_x509_name
attribute = _decode_x509_name_entry(backend, entry)
File "/usr/lib/python3.9/site-packages/cryptography/hazmat/backends/openssl/decode_asn1.py", line 54, in _decode_x509_name_entry
return x509.NameAttribute(x509.ObjectIdentifier(oid), value, type)
File "/usr/lib/python3.9/site-packages/cryptography/x509/name.py", line 91, in __init__
raise ValueError(
ValueError: Country name must be a 2 character country code
error: 127.0.0.1:55706: No TLS context was provided, failing connection.
error: 127.0.0.1:55706: mitmproxy has crashed!
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 279, in server_event
for command in layer_commands:
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 168, in handle_event
command = next(command_generator)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 255, in handle_event
yield from self._handle(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 168, in handle_event
command = next(command_generator)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 690, in _handle_event
yield from self.event_to_child(stream, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 740, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 168, in handle_event
command = next(command_generator)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 608, in passthrough
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 168, in handle_event
command = next(command_generator)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 85, in _handle_event
yield from self.event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 104, in event_to_child
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 168, in handle_event
command = next(command_generator)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 85, in _handle_event
yield from self.event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/tls.py", line 320, in event_to_child
yield from super().event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 104, in event_to_child
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 129, in handle_event
yield from self.__continue(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 220, in __continue
yield from self.__process(command_generator, event.reply)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 207, in __process
command = next(command_generator)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 61, in _handle_event
done, err = yield from self.receive_handshake_data(event.data)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/tls.py", line 381, in receive_handshake_data
yield from self.start_tls()
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/tls.py", line 173, in start_tls
assert tls_start.ssl_conn
AssertionError
info: 127.0.0.1:55706: Client TLS handshake failed. The client disconnected during the handshake. If this happens consistently for jonathanh.co.uk, this may
indicate that the client does not trust the proxy's certificate.
info: 127.0.0.1:55706: client disconnect
info: 127.0.0.1:55706: server disconnect 127.0.0.1:8081
```
| I added the `-k` flag in the hope that it would make mitmproxy ignore the fact
that it doesn't trust burp's certificate.
Thanks for the report! The problem here isn't `-k` in particular, but the fact that mitmproxy does not like the certificate generated by Burp. Do you happen to have a copy of the cert presented to the client?
In either case we'll get this fixed for the next patch release, a cert would just be nice to add a test. 😃
Here is the output of `openssl s_client -proxy 127.0.0.1:8081 -connect jonathanh.co.uk:443 | openssl x509 -noout -text`
```
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 128888301 (0x7aeaded)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = PortSwigger, ST = PortSwigger, L = PortSwigger, O = PortSwigger, OU = PortSwigger CA, CN = PortSwigger CA
Validity
Not Before: Jul 16 16:49:03 2021 GMT
Not After : Jul 16 16:49:03 2022 GMT
Subject: C = PortSwigger, O = PortSwigger, OU = PortSwigger CA, CN = jonathanh.co.uk
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:9a:29:92:4b:68:9f:93:d3:27:d7:7b:7d:99:4e:
18:b1:c2:67:99:f3:8c:a1:45:c5:b1:09:1e:36:e2:
9c:78:b6:79:36:7f:f0:73:33:5b:17:6d:26:c5:ee:
4c:eb:4e:7e:7b:44:d6:69:49:9e:d9:27:3b:a5:b6:
4d:02:6d:af:7b:69:7d:b1:f5:63:72:3c:b6:ac:f2:
a0:73:73:4c:13:b1:0d:e2:d8:18:78:ae:40:96:a6:
9b:7c:65:16:9a:7e:68:88:22:c1:91:b5:ef:a4:86:
db:94:95:cf:5f:90:a7:c4:3e:83:d3:cf:66:2c:a7:
79:1d:0f:c1:86:06:8d:33:5b:f8:49:ea:a0:94:a7:
64:d4:af:a5:cf:80:ab:42:b7:6b:8e:e7:23:03:39:
dd:5c:bd:c9:76:d8:2d:c2:5d:15:ff:cb:c5:f9:5a:
ac:ef:87:1f:cb:7f:f3:c0:a1:ea:34:9f:ae:1a:8f:
f6:d4:f8:2b:27:14:e4:95:66:0a:eb:c0:d4:bf:a1:
ee:5c:5a:e3:4b:43:08:c3:81:b3:f2:1c:82:46:bf:
a1:00:72:b8:e6:b4:a9:49:81:1b:a9:e1:bc:0b:57:
70:b0:30:cc:14:8b:44:c3:93:4e:1a:f0:70:02:8f:
4e:81:44:06:9e:4c:f4:6e:c5:da:82:95:59:5d:5b:
33:35
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Alternative Name:
DNS:jonathanh.co.uk
X509v3 Extended Key Usage:
TLS Web Server Authentication
Signature Algorithm: sha256WithRSAEncryption
34:84:d1:64:1e:ba:1a:8c:9c:ce:0d:0d:28:81:d0:fd:05:0c:
cb:88:2a:0e:bc:e6:09:fa:73:f6:a4:96:09:78:f9:e1:9b:05:
b5:28:f1:19:22:5e:8e:4e:a7:7f:ab:6d:11:7f:c2:94:f1:20:
61:75:a7:b7:08:16:a7:c3:80:45:96:c0:58:b6:95:d6:ba:88:
bf:21:45:b2:74:8d:8f:c2:69:bd:a5:d3:f6:00:5c:6a:1c:fa:
0c:fb:b8:d7:34:31:6e:1d:c7:5b:39:27:e3:a3:46:30:f5:f0:
29:e6:83:9b:30:c7:26:dd:67:2b:83:45:02:26:52:4e:12:de:
d2:69:01:80:09:ee:c9:23:94:8d:39:e7:5c:80:5c:48:f0:ba:
2c:e9:bf:27:d1:6d:3d:19:af:8f:f8:06:e5:be:79:5b:ca:65:
94:6b:a3:63:9c:7f:af:95:a4:c2:ce:0c:74:d8:c8:cf:dd:1a:
58:7f:1f:39:18:93:b9:bf:40:f4:b5:bc:43:1b:cd:d5:a8:71:
be:49:89:cc:e3:f3:dc:3d:66:3d:2d:ad:f2:62:65:fe:a9:3d:
60:2f:0d:20:cd:80:f6:b9:9d:0e:6d:f7:69:14:8d:f9:4b:70:
1e:e6:12:b4:96:41:da:74:64:16:a0:e8:8f:f2:b2:ed:c8:f6:
99:38:8c:d6
```
Is there anything else you need?
Also, I used the `-k` flag because I thought it would ignore the fact that
certificates are invalid / untrusted. Could you point me towards documentation on how I
should instruct mitmproxy to trust burp's CA?
So, it would appear that this is a result of the crypto library being used.
https://github.com/pyca/cryptography/blob/37103b3b65c5a41a7d4dd8cc00b09684f136c2d0/src/cryptography/x509/name.py#L92-L95
Is it worth opening an issue there?
The certificate that burp uses doesn't have a 2 letter country code. I am not
sure if that is a violtation of spec or just unusual but the crypto library
assumes that the country code will be two letters
https://github.com/pyca/cryptography/issues/3857
I've marked this as an upstream issue, not sure if we can workaround this easily.
For Burp Suite in particular it might be worth asking PortSwigger to fix their certificate.
I have created a bug report on the port swigger forums. Hopefully that will get sorted:
https://forum.portswigger.net/thread/valid-certificate-generated-8064875d | 2021-08-02T13:10:30 |
mitmproxy/mitmproxy | 4,725 | mitmproxy__mitmproxy-4725 | [
"4714"
] | 68cc3e721f1301779174421a455a30bca6d36206 | diff --git a/mitmproxy/addons/export.py b/mitmproxy/addons/export.py
--- a/mitmproxy/addons/export.py
+++ b/mitmproxy/addons/export.py
@@ -55,14 +55,14 @@ def request_content_for_console(request: http.Request) -> str:
)
-def curl_command(f: flow.Flow, preserve_ip: bool = False) -> str:
+def curl_command(f: flow.Flow) -> str:
request = cleanup_request(f)
request = pop_headers(request)
args = ["curl"]
server_addr = f.server_conn.peername[0] if f.server_conn.peername else None
- if preserve_ip and server_addr and request.pretty_host != server_addr:
+ if ctx.options.export_preserve_original_ip and server_addr and request.pretty_host != server_addr:
resolve = "{}:{}:[{}]".format(request.pretty_host, request.port, server_addr)
args.append("--resolve")
args.append(resolve)
@@ -102,30 +102,35 @@ def httpie_command(f: flow.Flow) -> str:
def raw_request(f: flow.Flow) -> bytes:
- return assemble.assemble_request(cleanup_request(f))
+ request = cleanup_request(f)
+ if request.raw_content is None:
+ raise exceptions.CommandError("Request content missing.")
+ return assemble.assemble_request(request)
def raw_response(f: flow.Flow) -> bytes:
- return assemble.assemble_response(cleanup_response(f))
+ response = cleanup_response(f)
+ if response.raw_content is None:
+ raise exceptions.CommandError("Response content missing.")
+ return assemble.assemble_response(response)
def raw(f: flow.Flow, separator=b"\r\n\r\n") -> bytes:
"""Return either the request or response if only one exists, otherwise return both"""
- request_present = hasattr(f, "request") and f.request # type: ignore
- response_present = hasattr(f, "response") and f.response # type: ignore
-
- if not (request_present or response_present):
- raise exceptions.CommandError("Can't export flow with no request or response.")
+ request_present = isinstance(f, http.HTTPFlow) and f.request and f.request.raw_content is not None
+ response_present = isinstance(f, http.HTTPFlow) and f.response and f.response.raw_content is not None
if request_present and response_present:
return b"".join([raw_request(f), separator, raw_response(f)])
- elif not request_present:
+ elif request_present:
+ return raw_request(f)
+ elif response_present:
return raw_response(f)
else:
- return raw_request(f)
+ raise exceptions.CommandError("Can't export flow with no request or response.")
-formats = dict(
+formats: typing.Dict[str, typing.Callable[[flow.Flow], typing.Union[str, bytes]]] = dict(
curl=curl_command,
httpie=httpie_command,
raw=raw,
@@ -134,7 +139,7 @@ def raw(f: flow.Flow, separator=b"\r\n\r\n") -> bytes:
)
-class Export():
+class Export:
def load(self, loader):
loader.add_option(
"export_preserve_original_ip", bool, False,
@@ -162,10 +167,7 @@ def file(self, format: str, flow: flow.Flow, path: mitmproxy.types.Path) -> None
if format not in formats:
raise exceptions.CommandError("No such export format: %s" % format)
func: typing.Any = formats[format]
- if format == "curl":
- v = func(flow, preserve_ip=ctx.options.export_preserve_original_ip)
- else:
- v = func(flow)
+ v = func(flow)
try:
with open(path, "wb") as fp:
if isinstance(v, bytes):
@@ -176,18 +178,16 @@ def file(self, format: str, flow: flow.Flow, path: mitmproxy.types.Path) -> None
ctx.log.error(str(e))
@command.command("export.clip")
- def clip(self, format: str, flow: flow.Flow) -> None:
+ def clip(self, format: str, f: flow.Flow) -> None:
"""
Export a flow to the system clipboard.
"""
if format not in formats:
raise exceptions.CommandError("No such export format: %s" % format)
- func: typing.Any = formats[format]
- if format == "curl":
- v = strutils.always_str(func(flow, preserve_ip=ctx.options.export_preserve_original_ip))
- else:
- v = strutils.always_str(func(flow))
+ func = formats[format]
+
+ val = strutils.always_str(func(f), "utf8", "backslashreplace")
try:
- pyperclip.copy(v)
+ pyperclip.copy(val)
except pyperclip.PyperclipException as e:
ctx.log.error(str(e))
| diff --git a/test/mitmproxy/addons/test_export.py b/test/mitmproxy/addons/test_export.py
--- a/test/mitmproxy/addons/test_export.py
+++ b/test/mitmproxy/addons/test_export.py
@@ -53,32 +53,40 @@ def tcp_flow():
return tflow.ttcpflow()
[email protected](scope="module")
+def export_curl():
+ e = export.Export()
+ with taddons.context() as tctx:
+ tctx.configure(e)
+ yield export.curl_command
+
+
class TestExportCurlCommand:
- def test_get(self, get_request):
+ def test_get(self, export_curl, get_request):
result = """curl -H 'header: qvalue' 'http://address:22/path?a=foo&a=bar&b=baz'"""
- assert export.curl_command(get_request) == result
+ assert export_curl(get_request) == result
- def test_post(self, post_request):
+ def test_post(self, export_curl, post_request):
post_request.request.content = b'nobinarysupport'
result = "curl -X POST http://address:22/path -d nobinarysupport"
- assert export.curl_command(post_request) == result
+ assert export_curl(post_request) == result
- def test_fails_with_binary_data(self, post_request):
+ def test_fails_with_binary_data(self, export_curl, post_request):
# shlex.quote doesn't support a bytes object
# see https://github.com/python/cpython/pull/10871
post_request.request.headers["Content-Type"] = "application/json; charset=utf-8"
with pytest.raises(exceptions.CommandError):
- export.curl_command(post_request)
+ export_curl(post_request)
- def test_patch(self, patch_request):
+ def test_patch(self, export_curl, patch_request):
result = """curl -H 'header: qvalue' -X PATCH 'http://address:22/path?query=param' -d content"""
- assert export.curl_command(patch_request) == result
+ assert export_curl(patch_request) == result
- def test_tcp(self, tcp_flow):
+ def test_tcp(self, export_curl, tcp_flow):
with pytest.raises(exceptions.CommandError):
- export.curl_command(tcp_flow)
+ export_curl(tcp_flow)
- def test_escape_single_quotes_in_body(self):
+ def test_escape_single_quotes_in_body(self, export_curl):
request = tflow.tflow(
req=tutils.treq(
method=b'POST',
@@ -86,31 +94,36 @@ def test_escape_single_quotes_in_body(self):
content=b"'&#"
)
)
- command = export.curl_command(request)
+ command = export_curl(request)
assert shlex.split(command)[-2] == '-d'
assert shlex.split(command)[-1] == "'&#"
- def test_strip_unnecessary(self, get_request):
+ def test_strip_unnecessary(self, export_curl, get_request):
get_request.request.headers.clear()
get_request.request.headers["host"] = "address"
get_request.request.headers[":authority"] = "address"
get_request.request.headers["accept-encoding"] = "br"
result = """curl --compressed 'http://address:22/path?a=foo&a=bar&b=baz'"""
- assert export.curl_command(get_request) == result
+ assert export_curl(get_request) == result
# This tests that we always specify the original host in the URL, which is
# important for SNI. If option `export_preserve_original_ip` is true, we
# ensure that we still connect to the same IP by using curl's `--resolve`
# option.
def test_correct_host_used(self, get_request):
- get_request.request.headers["host"] = "domain:22"
+ e = export.Export()
+ with taddons.context() as tctx:
+ tctx.configure(e)
- result = """curl -H 'header: qvalue' -H 'host: domain:22' 'http://domain:22/path?a=foo&a=bar&b=baz'"""
- assert export.curl_command(get_request) == result
+ get_request.request.headers["host"] = "domain:22"
- result = """curl --resolve 'domain:22:[192.168.0.1]' -H 'header: qvalue' -H 'host: domain:22' """ \
- """'http://domain:22/path?a=foo&a=bar&b=baz'"""
- assert export.curl_command(get_request, preserve_ip=True) == result
+ result = """curl -H 'header: qvalue' -H 'host: domain:22' 'http://domain:22/path?a=foo&a=bar&b=baz'"""
+ assert export.curl_command(get_request) == result
+
+ tctx.options.export_preserve_original_ip = True
+ result = """curl --resolve 'domain:22:[192.168.0.1]' -H 'header: qvalue' -H 'host: domain:22' """ \
+ """'http://domain:22/path?a=foo&a=bar&b=baz'"""
+ assert export.curl_command(get_request) == result
class TestExportHttpieCommand:
@@ -174,18 +187,12 @@ def test_get_request_present(self, 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')
+ get_response.request.content = None
assert b"header-response: svalue" in export.raw(get_response)
- def test_missing_both(self, get_request):
- delattr(get_request, 'request')
- delattr(get_request, 'response')
- with pytest.raises(exceptions.CommandError):
- export.raw(get_request)
-
def test_tcp(self, tcp_flow):
- with pytest.raises(exceptions.CommandError):
- export.raw_request(tcp_flow)
+ with pytest.raises(exceptions.CommandError, match="Can't export flow with no request or response"):
+ export.raw(tcp_flow)
class TestRawRequest:
@@ -193,10 +200,10 @@ 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')
+ def test_no_content(self, get_request):
+ get_request.request.content = None
with pytest.raises(exceptions.CommandError):
- export.raw_request(get_response)
+ export.raw_request(get_request)
def test_tcp(self, tcp_flow):
with pytest.raises(exceptions.CommandError):
@@ -207,9 +214,10 @@ class TestRawResponse:
def test_get(self, get_response):
assert b"header-response: svalue" in export.raw_response(get_response)
- def test_no_response(self, get_request):
+ def test_no_content(self, get_response):
+ get_response.response.content = None
with pytest.raises(exceptions.CommandError):
- export.raw_response(get_request)
+ export.raw_response(get_response)
def test_tcp(self, tcp_flow):
with pytest.raises(exceptions.CommandError):
@@ -221,8 +229,8 @@ def qr(f):
return fp.read()
-def test_export(tmpdir):
- f = str(tmpdir.join("path"))
+def test_export(tmp_path) -> None:
+ f = tmp_path / "outfile"
e = export.Export()
with taddons.context() as tctx:
tctx.configure(e)
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
@@ -136,7 +136,7 @@ def test_toggler():
o.toggler("one")
-class Rec():
+class Rec:
def __init__(self):
self.called = None
| "Cannot assemble flow with missing content" when exporting streamed flow in raw format
#### Problem Description
When a response (and possibly request, haven't checked that) is streamed and user tries to command `:export.clip raw @focus`, there is an exception:
```
Traceback (most recent call last):
File "/Users/korran/Projects/mitmproxy/mitmproxy/master.py", line 54, in run_loop
loop()
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/main_loop.py", line 287, in run
self._run()
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/main_loop.py", line 385, in _run
self.event_loop.run()
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/main_loop.py", line 1494, in run
reraise(*exc_info)
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/compat.py", line 58, in reraise
raise value
File "/usr/local/Cellar/[email protected]/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/raw_display.py", line 416, in <lambda>
wrapper = lambda: self.parse_input(
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/raw_display.py", line 515, in parse_input
callback(processed, processed_codes)
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/main_loop.py", line 412, in _update
self.process_input(keys)
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/main_loop.py", line 513, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/Users/korran/Projects/mitmproxy/mitmproxy/tools/console/window.py", line 316, in keypress
k = super().keypress(size, k)
File "/Users/korran/Projects/mitmproxy/venv/lib/python3.9/site-packages/urwid/container.py", line 1123, in keypress
return self.footer.keypress((maxcol,),key)
File "/Users/korran/Projects/mitmproxy/mitmproxy/tools/console/statusbar.py", line 201, in keypress
return self.ab.keypress(*args, **kwargs)
File "/Users/korran/Projects/mitmproxy/mitmproxy/tools/console/statusbar.py", line 149, in keypress
self.prompt_execute(text)
File "/Users/korran/Projects/mitmproxy/mitmproxy/tools/console/statusbar.py", line 169, in prompt_execute
msg = p(txt)
File "/Users/korran/Projects/mitmproxy/mitmproxy/tools/console/statusbar.py", line 115, in execute_command
execute(txt)
File "/Users/korran/Projects/mitmproxy/mitmproxy/tools/console/commandexecutor.py", line 18, in __call__
ret = self.master.commands.execute(cmd)
File "/Users/korran/Projects/mitmproxy/mitmproxy/command.py", line 273, in execute
return self.call_strings(command_name, args)
File "/Users/korran/Projects/mitmproxy/mitmproxy/command.py", line 259, in call_strings
return self.commands[command_name].call(args)
File "/Users/korran/Projects/mitmproxy/mitmproxy/command.py", line 129, in call
ret = self.func(*bound_args.args, **bound_args.kwargs)
File "/Users/korran/Projects/mitmproxy/mitmproxy/command.py", line 303, in wrapper
return function(*args, **kwargs)
File "/Users/korran/Projects/mitmproxy/mitmproxy/addons/export.py", line 189, in clip
v = strutils.always_str(func(flow))
File "/Users/korran/Projects/mitmproxy/mitmproxy/addons/export.py", line 121, in raw
return b"".join([raw_request(f), separator, raw_response(f)])
File "/Users/korran/Projects/mitmproxy/mitmproxy/addons/export.py", line 109, in raw_response
return assemble.assemble_response(cleanup_response(f))
File "/Users/korran/Projects/mitmproxy/mitmproxy/net/http/http1/assemble.py", line 17, in assemble_response
raise ValueError("Cannot assemble flow with missing content")
ValueError: Cannot assemble flow with missing content
```
#### Steps to reproduce the behavior:
1. Run mitmproxy with `--set stream_large_bodies=10k`
2. `curl -x 127.0.0.1 www.google.com 1>/dev/null`
3. `:export.clip raw @focus`
#### System Information
```
Mitmproxy: 8.0.0.dev (+17, commit 13131e2)
Python: 3.9.6
OpenSSL: OpenSSL 1.1.1i 8 Dec 2020
Platform: macOS-11.5.1-x86_64-i386-64bit
```
This exception is explicitly raised when `flow.response.content` is `None`, but I think it's still valuable to export whatever is available in a flow. I was thinking about setting some artificial content (or `b''`) for streamed request/response, but it doesn't seem like a good idea.
| Thanks for the clear report! 😃 | 2021-08-02T18:00:43 |
mitmproxy/mitmproxy | 4,730 | mitmproxy__mitmproxy-4730 | [
"4728"
] | 2ad3e5c698c2664f46cd497d8e51d39de2715e45 | diff --git a/mitmproxy/addons/tlsconfig.py b/mitmproxy/addons/tlsconfig.py
--- a/mitmproxy/addons/tlsconfig.py
+++ b/mitmproxy/addons/tlsconfig.py
@@ -106,17 +106,10 @@ def load(self, loader):
def tls_clienthello(self, tls_clienthello: tls.ClientHelloData):
conn_context = tls_clienthello.context
- only_non_http_alpns = (
- conn_context.client.alpn_offers and
- all(x not in tls.HTTP_ALPNS for x in conn_context.client.alpn_offers)
- )
tls_clienthello.establish_server_tls_first = conn_context.server.tls and (
ctx.options.connection_strategy == "eager" or
ctx.options.add_upstream_certs_to_client_chain or
- ctx.options.upstream_cert and (
- only_non_http_alpns or
- not conn_context.client.sni
- )
+ ctx.options.upstream_cert
)
def tls_start_client(self, tls_start: tls.TlsStartData) -> None:
@@ -288,7 +281,7 @@ def get_cert(self, conn_context: context.Context) -> certs.CertStoreEntry:
organization: Optional[str] = None
# Use upstream certificate if available.
- if conn_context.server.certificate_list:
+ if ctx.options.upstream_cert and conn_context.server.certificate_list:
upstream_cert = conn_context.server.certificate_list[0]
try:
# a bit clunky: access to .cn can fail, see https://github.com/mitmproxy/mitmproxy/issues/4713
diff --git a/mitmproxy/addons/upstream_auth.py b/mitmproxy/addons/upstream_auth.py
--- a/mitmproxy/addons/upstream_auth.py
+++ b/mitmproxy/addons/upstream_auth.py
@@ -51,7 +51,7 @@ def http_connect_upstream(self, f: http.HTTPFlow):
def requestheaders(self, f: http.HTTPFlow):
if self.auth:
- if f.mode == "upstream" and not f.server_conn.via:
+ if ctx.options.mode.startswith("upstream") and f.request.scheme == "http":
f.request.headers["Proxy-Authorization"] = self.auth
elif ctx.options.mode.startswith("reverse"):
f.request.headers["Authorization"] = self.auth
diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -173,7 +173,7 @@ async def open_connection(self, command: commands.OpenConnection) -> None:
assert command.connection.peername
if command.connection.address[0] != command.connection.peername[0]:
- addr = f"{command.connection.address[0]} ({human.format_address(command.connection.peername)})"
+ addr = f"{human.format_address(command.connection.address)} ({human.format_address(command.connection.peername)})"
else:
addr = human.format_address(command.connection.address)
self.log(f"server connect {addr}")
| diff --git a/mitmproxy/test/tflow.py b/mitmproxy/test/tflow.py
--- a/mitmproxy/test/tflow.py
+++ b/mitmproxy/test/tflow.py
@@ -10,7 +10,7 @@
from wsproto.frame_protocol import Opcode
-def ttcpflow(client_conn=True, server_conn=True, messages=True, err=None):
+def ttcpflow(client_conn=True, server_conn=True, messages=True, err=None) -> tcp.TCPFlow:
if client_conn is True:
client_conn = tclient_conn()
if server_conn is True:
@@ -91,7 +91,7 @@ def twebsocketflow(messages=True, err=None, close_code=None, close_reason='') ->
return flow
-def tflow(client_conn=True, server_conn=True, req=True, resp=None, err=None):
+def tflow(client_conn=True, server_conn=True, req=True, resp=None, err=None) -> http.HTTPFlow:
"""
@type client_conn: bool | None | mitmproxy.proxy.connection.ClientConnection
@type server_conn: bool | None | mitmproxy.proxy.connection.ServerConnection
@@ -126,7 +126,7 @@ def __init__(self, client_conn, server_conn, live=None):
super().__init__("dummy", client_conn, server_conn, live)
-def tdummyflow(client_conn=True, server_conn=True, err=None):
+def tdummyflow(client_conn=True, server_conn=True, err=None) -> DummyFlow:
if client_conn is True:
client_conn = tclient_conn()
if server_conn is True:
diff --git a/test/mitmproxy/addons/test_upstream_auth.py b/test/mitmproxy/addons/test_upstream_auth.py
--- a/test/mitmproxy/addons/test_upstream_auth.py
+++ b/test/mitmproxy/addons/test_upstream_auth.py
@@ -33,20 +33,18 @@ def test_simple():
tctx.configure(up, upstream_auth="foo:bar")
f = tflow.tflow()
- f.mode = "upstream"
- up.requestheaders(f)
+ up.http_connect_upstream(f)
assert "proxy-authorization" in f.request.headers
f = tflow.tflow()
up.requestheaders(f)
assert "proxy-authorization" not in f.request.headers
+ assert "authorization" not in f.request.headers
+
+ tctx.configure(up, mode="upstream:127.0.0.1")
+ up.requestheaders(f)
+ assert "proxy-authorization" in f.request.headers
tctx.configure(up, mode="reverse:127.0.0.1")
- f = tflow.tflow()
- f.mode = "transparent"
up.requestheaders(f)
assert "authorization" in f.request.headers
-
- f = tflow.tflow()
- up.http_connect_upstream(f)
- assert "proxy-authorization" in f.request.headers
| Upstream auth for NordVPN does not work
#### Problem Description
Using an upstream authenticated NordVPN proxy does not work. Even though credentials are specified in the command line, the browser still asks for them.
#### Steps to reproduce the behavior:
1. `mitmdump --ssl-insecure --mode "upstream:https://de873.nordvpn.com:89" --upstream-auth "USER:PASS" `
2. `google-chrome --proxy-server="http://localhost:8080"`
```
Proxy server listening at http://*:8080
[::1]:40966: client connect
[::1]:40968: client connect
[::1]:40968: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40966: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40970: client connect
[::1]:40972: client connect
[::1]:40972: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40970: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40974: client connect
[::1]:40974: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40976: client connect
[::1]:40978: client connect
[::1]:40968: POST https://accounts.google.com/ListAccounts?gpsia=1&source=ChromiumBrowser&json=standard HTTP/2.0
<< HTTP/2.0 200 OK 43b
[::1]:40980: client connect
[::1]:40982: client connect
[::1]:40966: GET https://clientservices.googleapis.com/chrome-variations/seed?osname=linux&channel=stable&milestone=92 HTTP/2.0
<< HTTP/2.0 200 OK 24.31k
[::1]:40976: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40978: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40984: client connect
[::1]:40982: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40980: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40986: client connect
[::1]:40988: client connect
[::1]:40984: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40986: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40988: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40974: GET https://ssl.google-analytics.com/ga.js HTTP/2.0
<< HTTP/2.0 200 OK 16.77k
[::1]:40990: client connect
[::1]:40992: client connect
[::1]:40994: client connect
[::1]:40976: GET https://api.github.com/repos/keepassxreboot/keepassxc/releases/latest HTTP/2.0
<< HTTP/2.0 200 OK 3.32k
[::1]:40978: POST https://www.googleapis.com/oauth2/v4/token HTTP/2.0
<< HTTP/2.0 200 OK 1.09k
[::1]:40996: client connect
[::1]:40980: GET https://www.google-analytics.com/analytics.js HTTP/2.0
<< HTTP/2.0 200 OK 19.21k
[::1]:40980: GET https://www.google-analytics.com/r/__utm.gif?utmwv=5.7.2&utms=24&utmn=729937857&utmhn=fngmhnnpilhplaeedifhccceomclgfbg&utmcs=UTF-8&utmsr=1920x1080&utmsc=24-bit&utmul… HTTP/2.0
<< HTTP/2.0 302 Found 368b
[::1]:40994: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40990: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40992: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40998: client connect
[::1]:40996: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40984: GET https://cdn.honey.io/standdown-rules.json HTTP/2.0
<< HTTP/2.0 200 OK 16.86k
[::1]:40982: GET https://accounts.google.com/GetCheckConnectionInfo?source=ChromiumBrowser HTTP/2.0
<< HTTP/2.0 200 OK 169b
[::1]:41000: client connect
[::1]:41002: client connect
[::1]:40998: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40988: GET https://safebrowsing.googleapis.com/v4/fullHashes:find?$req=Ch0KDGdvb2dsZWNocm9tZRINOTIuMC40NTE1LjEzMRIbCg0IBxAGGAEiAzAwMTABEMv-CBoCGAZybqRJEhsKDQgFEAYYASIDMDAxMAEQx… HTTP/2.0
<< HTTP/2.0 200 OK 82b
[::1]:41002: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41000: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40990: Client TLS handshake failed. The client disconnected during the handshake. If this happens consistently for d.joinhoney.com, this may indicate that the client does not trust the proxy's certificate.
[::1]:40990: client disconnect
[::1]:40990: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40992: GET https://d.joinhoney.com/features/pay_now_enabled?serviceName=honey-extension&serviceVersion=13.0.1 HTTP/2.0
<< HTTP/2.0 200 OK 15b
[::1]:40992: GET https://d.joinhoney.com/adb/filter HTTP/2.0
<< HTTP/2.0 200 OK 485b
[::1]:40992: GET https://d.joinhoney.com/features/ext_paypal_heartbeat?serviceName=honey-extension&serviceVersion=13.0.1 HTTP/2.0
<< HTTP/2.0 200 OK 15b
[::1]:41004: client connect
[::1]:41006: client connect
[::1]:41010: client connect
[::1]:41014: client connect
[::1]:40992: GET https://d.joinhoney.com/v3?operationName=ext_getUserInfo&variables=%7B%7D HTTP/2.0
<< HTTP/2.0 401 Unauthorized 26b
[::1]:41004: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40998: GET https://stats.g.doubleclick.net/r/collect?v=1&aip=1&t=dc&_r=3&tid=UA-33054271-5&cid=66718305.1595413759&jid=1562794097&_v=5.7.2&z=729937857 HTTP/2.0
<< HTTP/2.0 200 OK 35b
[::1]:41018: client connect
[::1]:41006: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41014: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41010: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40992: GET https://d.joinhoney.com/extdata/ckdata HTTP/2.0
<< HTTP/2.0 200 OK 2b
[::1]:41018: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41020: client connect
[::1]:41024: client connect
[::1]:41026: client connect
[::1]:41028: client connect
[::1]:41020: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40992: GET https://d.joinhoney.com/v3?operationName=ext_getExperiments&variables=%7B%22platform%22%3A%22ext%22%2C%22archived%22%3Afalse%7D HTTP/2.0
<< HTTP/2.0 200 OK 34.17k
[::1]:40992: GET https://d.joinhoney.com/v3?operationName=checkout_getURLObservationRemoteConfig&variables=%7B%7D HTTP/2.0
<< HTTP/2.0 200 OK 130b
[::1]:41024: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41028: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41026: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41030: client connect
[::1]:40972: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:40986: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:40972: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40986: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40970: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:40994: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:40996: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:41006: GET https://clients2.google.com/service/update2/crx?os=linux&arch=x64&os_arch=x86_64&nacl_arch=x86-64&prod=chromecrx&prodchannel=&prodversion=92.0.4515.131&lang=en-US&ac… HTTP/2.0
<< HTTP/2.0 200 OK 448b
[::1]:41002: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:40986: client disconnect
[::1]:40970: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40994: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40996: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41002: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40994: client disconnect
[::1]:41010: mitmproxy has crashed!
Traceback (most recent call last):
File "/home/torstein/anaconda3/lib/python3.8/site-packages/mitmproxy/proxy/server.py", line 282, in server_event
assert command.connection not in self.transports
AssertionError
[::1]:41030: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41014: POST https://android.clients.google.com/c2dm/register3 HTTP/2.0
<< HTTP/2.0 200 OK 158b
[::1]:41014: POST https://android.clients.google.com/checkin HTTP/2.0
<< HTTP/2.0 200 OK 397b
[::1]:40996: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41002: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40972: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40970: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41004: GET https://history.paypal.com/targeting/set-plugin?src=honey
<< 200 OK 59b
[::1]:41028: client disconnect
[::1]:41028: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41026: client disconnect
[::1]:41026: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41014: POST https://android.clients.google.com/c2dm/register3 HTTP/2.0
<< HTTP/2.0 200 OK 167b
[::1]:41014: POST https://android.clients.google.com/c2dm/register3 HTTP/2.0
<< HTTP/2.0 200 OK 168b
[::1]:41020: POST https://s.joinhoney.com/ev/ext000001 HTTP/2.0
<< HTTP/2.0 200 OK 2b
[::1]:41020: POST https://s.joinhoney.com/evs HTTP/2.0
<< HTTP/2.0 200 OK 2b
[::1]:41030: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:41000: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:40970: GET https://www.httpbin.org/ip HTTP/2.0
<< Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required
[::1]:40972: POST https://safebrowsing.google.com/safebrowsing/clientreport/realtime HTTP/2.0
<< Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required
[::1]:40996: POST https://oauthaccountmanager.googleapis.com/v1/issuetoken HTTP/2.0
<< Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required
[::1]:41002: GET https://accounts.youtube.com/accounts/CheckConnection?chromeCheckConnection=1&v=284156175 HTTP/2.0
<< Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required
[::1]:41030: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41000: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40970: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40972: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40996: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41002: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41030: client disconnect
[::1]:41018: POST https://update.googleapis.com/service/update2/json?cup2key=11:2131373072&cup2hreq=29bddc46f920bab8cdb45419334543ebc8858a931a2ab51559eb45e9275fee6d HTTP/2.0
<< HTTP/2.0 200 OK 3.28k
[::1]:41032: client connect
[::1]:41032: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41000: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40978: POST https://www.googleapis.com/oauth2/v4/token HTTP/2.0
<< HTTP/2.0 200 OK 353b
[::1]:40970: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:40978: POST https://www.googleapis.com/oauth2/v4/token HTTP/2.0
<< HTTP/2.0 200 OK 347b
[::1]:41034: client connect
[::1]:41036: client connect
[::1]:41036: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41034: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41038: client connect
[::1]:41042: client connect
[::1]:41044: client connect
[::1]:41046: client connect
[::1]:41048: client connect
[::1]:41024: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:41024: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41024: client disconnect
[::1]:41046: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41042: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41038: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41048: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41044: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41032: GET https://clients2.googleusercontent.com/crx/blobs/Acy1k0aSwbfD1gHSR7DV9HG6UjXpqJ2bHXPyin3BM_eq0vJ9e-NXxb_8MMsXjQi1WL90l1aSTEL5cV_4yM0t8ZMgoVqdMxVLqvQABx44nreL68p0xAUc… HTTP/2.0
<< HTTP/2.0 200 OK 46.56k
[::1]:41018: POST https://update.googleapis.com/service/update2/json HTTP/2.0
<< HTTP/2.0 200 OK 170b
[::1]:41044: Client TLS handshake failed. The client disconnected during the handshake. If this happens consistently for firebaseperusertopics-pa.googleapis.com, this may indicate that the client does not trust the proxy's certificate.
[::1]:41044: client disconnect
[::1]:41044: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41042: client disconnect
[::1]:41042: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40970: GET https://www.httpbin.org/favicon.ico HTTP/2.0
<< HTTP/2.0 404 Not Found 233b
[::1]:41046: client disconnect
[::1]:41046: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 97b
[::1]:41038: client disconnect
[::1]:41038: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 91b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 100b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 100b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 97b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 96b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 99b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 104b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 98b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 102b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 94b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 103b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 105b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 96b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 93b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 104b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 108b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 113b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 102b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 98b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 106b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 97b
[::1]:41048: POST https://firebaseperusertopics-pa.googleapis.com/v1/perusertopics/8181035976/rel/topics/?subscriber_token=dnsZI3fGpQw:APA91bFhWoT0CyXu5VQdog5Eua5Q03RTEv6ysrCPpUJ54aiJ… HTTP/2.0
<< HTTP/2.0 200 OK 99b
[::1]:41000: GET https://accounts.doubleclick.net/CheckConnection?chromeCheckConnection=1&v=1819058658 HTTP/2.0
<< Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required
[::1]:41000: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40984: GET https://cdn.honey.io/experiments.json HTTP/2.0
<< HTTP/2.0 200 OK 111.32k
[::1]:41036: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:41036: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41034: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:41036: client disconnect
[::1]:41034: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41050: client connect
[::1]:41052: client connect
[::1]:41054: client connect
[::1]:41034: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41052: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41050: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41054: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41052: HEAD http://smctajrvnogvwb/
<< 407 Proxy Authentication Required 0b
[::1]:41052: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41052: client disconnect
[::1]:41050: HEAD http://albefeg/
<< 407 Proxy Authentication Required 0b
[::1]:41050: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41054: HEAD http://kiradqwtwzyikhb/
<< 407 Proxy Authentication Required 0b
[::1]:41054: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41050: client disconnect
[::1]:41054: client disconnect
[::1]:41034: POST https://clients4.google.com/chrome-sync/command/?client=Google+Chrome&client_id=8Y%2Bn4uCpr7joqrFhFEAVdw%3D%3D HTTP/2.0
<< HTTP/2.0 200 OK 21.75k
[::1]:40968: POST https://accounts.google.com/oauth/multilogin?source=ChromiumAccountReconcilorDice&reuseCookies=1&externalCcResult=doubleclick:null,youtube:null HTTP/2.0
<< HTTP/2.0 200 OK 1.16k
[::1]:40968: POST https://accounts.google.com/ListAccounts?gpsia=1&source=ChromiumBrowser&json=standard HTTP/2.0
<< HTTP/2.0 200 OK 197b
[::1]:41014: POST https://android.clients.google.com/c2dm/register3 HTTP/2.0
<< HTTP/2.0 200 OK 166b
[::1]:41014: POST https://android.clients.google.com/c2dm/register3 HTTP/2.0
<< HTTP/2.0 200 OK 166b
[::1]:41034: POST https://clients4.google.com/chrome-sync/command/?client=Google+Chrome&client_id=8Y%2Bn4uCpr7joqrFhFEAVdw%3D%3D HTTP/2.0
<< HTTP/2.0 200 OK 125.57k
[::1]:41034: POST https://clients4.google.com/chrome-sync/command/?client=Google+Chrome&client_id=8Y%2Bn4uCpr7joqrFhFEAVdw%3D%3D HTTP/2.0
<< HTTP/2.0 200 OK 31.34k
[::1]:41006: GET https://clients2.google.com/service/update2/crx?os=linux&arch=x64&os_arch=x86_64&nacl_arch=x86-64&prod=chromecrx&prodchannel=&prodversion=92.0.4515.131&lang=en-US&ac… HTTP/2.0
<< HTTP/2.0 200 OK 448b
[::1]:41034: POST https://clients4.google.com/chrome-sync/command/?client=Google+Chrome&client_id=8Y%2Bn4uCpr7joqrFhFEAVdw%3D%3D HTTP/2.0
<< HTTP/2.0 200 OK 354b
[::1]:41034: POST https://clients4.google.com/chrome-sync/command/?client=Google+Chrome&client_id=8Y%2Bn4uCpr7joqrFhFEAVdw%3D%3D HTTP/2.0
<< HTTP/2.0 200 OK 898b
[::1]:40992: GET https://d.joinhoney.com/v3?operationName=ext_getSupportedDomains&variables=%7B%7D HTTP/2.0
<< HTTP/2.0 200 OK 1.81m
[::1]:41056: client connect
[::1]:41056: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41056: Unable to establish TLS connection with server (Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required). Trying to establish TLS with client anyway.
[::1]:41056: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41056: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41058: client connect
[::1]:41058: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41058: GET http://www.httpbin.org/ip
<< 407 Proxy Authentication Required 4.96k
[::1]:41058: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41058: client disconnect
[::1]:41060: client connect
[::1]:41056: GET https://www.google.com/complete/search?client=chrome-omni&gs_ri=chrome-ext-ansg&xssi=t&q=http%3A%2F%2Fwww.httpbin.org%2Fip&oit=3&cp=4&url=https%3A%2F%2Fwww.httpbin.o… HTTP/2.0
<< Upstream proxy de873.nordvpn.com:89 refused HTTP CONNECT request: 407 Proxy Authentication Required
[::1]:41056: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41060: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41060: GET http://www.httpbin.org/ip
<< 407 Proxy Authentication Required 4.96k
[::1]:41060: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41060: client disconnect
[::1]:41062: client connect
[::1]:41062: server connect de873.nordvpn.com (185.220.70.210:89)
[::1]:41062: client disconnect
[::1]:41062: Server TLS handshake failed. connection closed
[::1]:41062: GET http://www.httpbin.org/favicon.ico
<< connection closed
[::1]:41062: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:40988: client disconnect
[::1]:40972: client disconnect
[::1]:40988: server disconnect de873.nordvpn.com (185.220.70.210:89)
[::1]:41034: POST https://clients4.google.com/chrome-sync/command/?client=Google+Chrome&client_id=8Y%2Bn4uCpr7joqrFhFEAVdw%3D%3D HTTP/2.0
<< stream reset by client (CANCEL)
[::1]:40968: client disconnect
[::1]:40974: client disconnect
[::1]:40978: client disconnect
[::1]:41032: GET https://clients2.googleusercontent.com/crx/blobs/Acy1k0Yj5Kgw06-BW554OtkZlHd2iS5w3YnDgN37ZTR5xhCFn0NBbk9nxgZxGRWMRGPYBdDgjgGeKPafBs-NTzCmAxfbMoV4EhecM8j60dkC4KElemE4… HTTP/2.0
<< HTTP/2.0 200 OK (content missing)
<< peer closed connection
[::1]:40982: client disconnect
[::1]:40976: client disconnect
[::1]:40980: client disconnect
[::1]:40984: client disconnect
[::1]:40992: client disconnect
[::1]:40998: client disconnect
```
#### System Information
```
mitmdump --version (base) 3.7m
Mitmproxy: 7.0.0
Python: 3.8.8
OpenSSL: OpenSSL 1.1.1i 8 Dec 2020
Platform: Linux-5.12.15-200.fc33.x86_64-x86_64-with-glibc2.10
```
| Thanks! This is much more useful already. It looks like some requests are getting through, while we get `407 Proxy Authentication Required` for others? Can you confirm this? If so, a full debug log with `-vvv --set proxy_debug` would be tremendously helpful. Feel free to shoot it by email if it contains potententially sensitive data. Upstream auth works fine for me locally, I can't reproduce this yet. | 2021-08-03T15:04:04 |
mitmproxy/mitmproxy | 4,731 | mitmproxy__mitmproxy-4731 | [
"4696"
] | aa2abb9bf4e46f8b0654c16ab45aeb76c8331684 | diff --git a/mitmproxy/utils/human.py b/mitmproxy/utils/human.py
--- a/mitmproxy/utils/human.py
+++ b/mitmproxy/utils/human.py
@@ -1,30 +1,34 @@
import datetime
+import functools
import ipaddress
import time
-import functools
import typing
-SIZE_TABLE = [
- ("b", 1024 ** 0),
- ("k", 1024 ** 1),
- ("m", 1024 ** 2),
- ("g", 1024 ** 3),
- ("t", 1024 ** 4),
-]
-
-SIZE_UNITS = dict(SIZE_TABLE)
-
-
-def pretty_size(size):
- for bottom, top in zip(SIZE_TABLE, SIZE_TABLE[1:]):
- if bottom[1] <= size < top[1]:
- suf = bottom[0]
- lim = bottom[1]
- x = round(size / lim, 2)
- if x == int(x):
- x = int(x)
- return str(x) + suf
- return "{}{}".format(size, SIZE_TABLE[0][0])
+
+SIZE_UNITS = {
+ "b": 1024 ** 0,
+ "k": 1024 ** 1,
+ "m": 1024 ** 2,
+ "g": 1024 ** 3,
+ "t": 1024 ** 4,
+}
+
+
+def pretty_size(size: int) -> str:
+ """Convert a number of bytes into a human-readable string.
+
+ len(return value) <= 5 always holds true.
+ """
+ s: float = size # type cast for mypy
+ if s < 1024:
+ return f"{s}b"
+ for suffix in ["k", "m", "g", "t"]:
+ s /= 1024
+ if s < 99.95:
+ return f"{s:.1f}{suffix}"
+ if s < 1024 or suffix == "t":
+ return f"{s:.0f}{suffix}"
+ raise AssertionError
@functools.lru_cache()
| 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
@@ -28,10 +28,11 @@ def test_parse_size():
def test_pretty_size():
assert human.pretty_size(0) == "0b"
assert human.pretty_size(100) == "100b"
- assert human.pretty_size(1024) == "1k"
- assert human.pretty_size(1024 + (1024 / 2.0)) == "1.5k"
- assert human.pretty_size(1024 * 1024) == "1m"
- assert human.pretty_size(10 * 1024 * 1024) == "10m"
+ assert human.pretty_size(1024) == "1.0k"
+ assert human.pretty_size(1024 + 512) == "1.5k"
+ assert human.pretty_size(1024 * 1024) == "1.0m"
+ assert human.pretty_size(10 * 1024 * 1024) == "10.0m"
+ assert human.pretty_size(100 * 1024 * 1024) == "100m"
def test_pretty_duration():
| Improve Rendering of the Size Column
#### Problem Description
The size column currently renders really badly:

`….64k` clearly is not what the user is interested in, something like `204k` would be much more useful.
#### Steps to reproduce the behavior:
1. Access a file with a size that is larger than 10kb, but smaller than 1MB.
#### Proposed fix
In short, we want to have a string here with a maximum length of 5 characters so that it does not get truncated. My proposal would be to just round to the nearest integer, e.g. `204k` instead of `204.64k`.
The relevant code is here:
https://github.com/mitmproxy/mitmproxy/blob/e270399a3eba7b3212bf7325beaa50e159a7ca0a/mitmproxy/utils/human.py#L18-L27
and the accompanying tests are here:
https://github.com/mitmproxy/mitmproxy/blob/0ca458fd6475ee48728147f3b529467a75e912a4/test/mitmproxy/utils/test_human.py#L28-L34
Fixing this should be really straightforward, so I'm leaving this open for new contributors. 😃
#### System Information
```
Mitmproxy: 8.0.0.dev (+15, commit e270399)
Python: 3.9.4
OpenSSL: OpenSSL 1.1.1f 31 Mar 2020
Platform: Linux-4.4.0-19041-Microsoft-x86_64-with-glibc2.31
```
| Hi, I'm fairly new to contributing to open source in general and I'd be happy to work on this when I can.
@aaron-tan: Excellent! We have a CONTRIBUTING.md in the repo that details how to set up a dev environment and run the tests. If you have any (stupid) questions please don't hesitate to ask here or ping me or anyone else on Slack! :)
Hi, I'm trying to reproduce the behavior but I don't seem able to. Here's a screenshot of what I see on my mitmproxy.

I wasn't really sure what you meant in the steps to reproduce, I assumed you were talking about the flows so I tried getting a flow that fit the criteria but it's still displayed in full. Do you mind elaborating on the steps to reproduce?
You need to increase the width of your console window (or decrease the font size) so that mitmproxy switches to a tabular view. :) | 2021-08-04T11:20:24 |
mitmproxy/mitmproxy | 4,741 | mitmproxy__mitmproxy-4741 | [
"4735",
"4735"
] | 1ce7e8e02e6424cf5ed87f23a98aa27a0f803846 | diff --git a/mitmproxy/net/encoding.py b/mitmproxy/net/encoding.py
--- a/mitmproxy/net/encoding.py
+++ b/mitmproxy/net/encoding.py
@@ -52,6 +52,7 @@ def decode(
"""
if encoded is None:
return None
+ encoding = encoding.lower()
global _cache
cached = (
@@ -67,7 +68,7 @@ def decode(
decoded = custom_decode[encoding](encoded)
except KeyError:
decoded = codecs.decode(encoded, encoding, errors) # type: ignore
- if encoding in ("gzip", "deflate", "br", "zstd"):
+ if encoding in ("gzip", "deflate", "deflateraw", "br", "zstd"):
_cache = CachedDecode(encoded, encoding, errors, decoded)
return decoded
except TypeError:
@@ -108,6 +109,7 @@ def encode(decoded: Union[None, str, bytes], encoding, errors='strict') -> Union
"""
if decoded is None:
return None
+ encoding = encoding.lower()
global _cache
cached = (
@@ -123,7 +125,7 @@ def encode(decoded: Union[None, str, bytes], encoding, errors='strict') -> Union
encoded = custom_encode[encoding](decoded)
except KeyError:
encoded = codecs.encode(decoded, encoding, errors) # type: ignore
- if encoding in ("gzip", "deflate", "br", "zstd"):
+ if encoding in ("gzip", "deflate", "deflateraw", "br", "zstd"):
_cache = CachedDecode(encoded, encoding, errors, decoded)
return encoded
except TypeError:
@@ -216,7 +218,7 @@ def encode_deflate(content: bytes) -> bytes:
"identity": identity,
"gzip": decode_gzip,
"deflate": decode_deflate,
- "deflateRaw": decode_deflate,
+ "deflateraw": decode_deflate,
"br": decode_brotli,
"zstd": decode_zstd,
}
@@ -225,7 +227,7 @@ def encode_deflate(content: bytes) -> bytes:
"identity": identity,
"gzip": encode_gzip,
"deflate": encode_deflate,
- "deflateRaw": encode_deflate,
+ "deflateraw": encode_deflate,
"br": encode_brotli,
"zstd": encode_zstd,
}
| diff --git a/test/mitmproxy/net/test_encoding.py b/test/mitmproxy/net/test_encoding.py
--- a/test/mitmproxy/net/test_encoding.py
+++ b/test/mitmproxy/net/test_encoding.py
@@ -17,6 +17,7 @@ def test_identity(encoder):
@pytest.mark.parametrize("encoder", [
'gzip',
+ 'GZIP',
'br',
'deflate',
'zstd',
| GZIP request body encoding falling back to raw
#### Problem Description
GZIP requests are not decoded correctly.
This only occurs in the request and not in the response. In the response I see the body as uncompromised gzip but not in the request.
I created a own content view to test the gzip decompression:
```python
from typing import Optional
from mitmproxy import contentviews, flow
from mitmproxy import http
import gzip
class ViewGZIPCase(contentviews.View):
name = "GZIP"
def __call__(self, data, **metadata) -> contentviews.TViewResult:
return "gzip", contentviews.format_text(gzip.decompress(data))
def render_priority(
self,
data: bytes,
*,
content_type: Optional[str] = None,
flow: Optional[flow.Flow] = None,
http_message: Optional[http.Message] = None,
**unknown_metadata,
) -> float:
if http_message.headers["content-encoding"] == "GZIP":
return 1
else:
return 0
view = ViewGZIPCase()
def load(l):
contentviews.add(view)
def done():
contentviews.remove(view)
```
##### request
with selected self-made view
<img width="1637" alt="Screenshot 2021-08-05 at 16 42 57" src="https://user-images.githubusercontent.com/1338331/128370647-68c5af49-dfca-4862-a3ff-b3413c4226fd.png">
without any special view
<img width="1637" alt="Screenshot 2021-08-05 at 16 42 42" src="https://user-images.githubusercontent.com/1338331/128370652-e2001fd6-0909-491a-8c77-19cfa226b7d6.png">
##### response
Mitmproxy standalone decompression and json parsing in the response but why not in the request?
<img width="1637" alt="Screenshot 2021-08-05 at 16 47 55" src="https://user-images.githubusercontent.com/1338331/128370639-75287a4f-5c54-47e9-a126-3ff95a1dc90f.png">
#### Steps to reproduce the behavior:
1. start Mitmproxy
2. wait for requests ( iPhone 12 as client is connected)
3. open the request
#### System Information
Mitmproxy: 7.0.2
Python: 3.9.6
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: macOS-11.5.1-x86_64-i386-64bit
GZIP request body encoding falling back to raw
#### Problem Description
GZIP requests are not decoded correctly.
This only occurs in the request and not in the response. In the response I see the body as uncompromised gzip but not in the request.
I created a own content view to test the gzip decompression:
```python
from typing import Optional
from mitmproxy import contentviews, flow
from mitmproxy import http
import gzip
class ViewGZIPCase(contentviews.View):
name = "GZIP"
def __call__(self, data, **metadata) -> contentviews.TViewResult:
return "gzip", contentviews.format_text(gzip.decompress(data))
def render_priority(
self,
data: bytes,
*,
content_type: Optional[str] = None,
flow: Optional[flow.Flow] = None,
http_message: Optional[http.Message] = None,
**unknown_metadata,
) -> float:
if http_message.headers["content-encoding"] == "GZIP":
return 1
else:
return 0
view = ViewGZIPCase()
def load(l):
contentviews.add(view)
def done():
contentviews.remove(view)
```
##### request
with selected self-made view
<img width="1637" alt="Screenshot 2021-08-05 at 16 42 57" src="https://user-images.githubusercontent.com/1338331/128370647-68c5af49-dfca-4862-a3ff-b3413c4226fd.png">
without any special view
<img width="1637" alt="Screenshot 2021-08-05 at 16 42 42" src="https://user-images.githubusercontent.com/1338331/128370652-e2001fd6-0909-491a-8c77-19cfa226b7d6.png">
##### response
Mitmproxy standalone decompression and json parsing in the response but why not in the request?
<img width="1637" alt="Screenshot 2021-08-05 at 16 47 55" src="https://user-images.githubusercontent.com/1338331/128370639-75287a4f-5c54-47e9-a126-3ff95a1dc90f.png">
#### Steps to reproduce the behavior:
1. start Mitmproxy
2. wait for requests ( iPhone 12 as client is connected)
3. open the request
#### System Information
Mitmproxy: 7.0.2
Python: 3.9.6
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: macOS-11.5.1-x86_64-i386-64bit
| Thanks for the super clear report! Here's what we do for gzip:
https://github.com/mitmproxy/mitmproxy/blob/7efefb716eb004369a264491f0ca558e32337c8a/mitmproxy/net/encoding.py#L148
Would you mind plugging your own gzip decompression in there to see if that helps? We're really just using Python's standard library here. Alternatively, a saved flow would be really helpful.
I'm just throwing out there that the `GZIP` is upper case in the request. Not sure if we handle that? Didn't look into it.
Good catch, @Prinzhorn! Content-Encoding is case-insensitive (https://datatracker.ietf.org/doc/html/rfc7231#section-3.1.2.1), so this is a mitmproxy bug. :)
Maybe [this line](https://github.com/mitmproxy/mitmproxy/blob/0ca458fd6475ee48728147f3b529467a75e912a4/mitmproxy/net/encoding.py#L70) needs to read
```py
if isinstance(encoding, str) and encoding.lower() in ("gzip", "deflate", "br", "zstd"):
```
instead of
```py
if encoding in ("gzip", "deflate", "br", "zstd"):
```
Thank you all. I'll try the whole thing and test it.
Many thanks to @Mattwmaster58 for the pull request.
Thanks for the super clear report! Here's what we do for gzip:
https://github.com/mitmproxy/mitmproxy/blob/7efefb716eb004369a264491f0ca558e32337c8a/mitmproxy/net/encoding.py#L148
Would you mind plugging your own gzip decompression in there to see if that helps? We're really just using Python's standard library here. Alternatively, a saved flow would be really helpful.
I'm just throwing out there that the `GZIP` is upper case in the request. Not sure if we handle that? Didn't look into it.
Good catch, @Prinzhorn! Content-Encoding is case-insensitive (https://datatracker.ietf.org/doc/html/rfc7231#section-3.1.2.1), so this is a mitmproxy bug. :)
Maybe [this line](https://github.com/mitmproxy/mitmproxy/blob/0ca458fd6475ee48728147f3b529467a75e912a4/mitmproxy/net/encoding.py#L70) needs to read
```py
if isinstance(encoding, str) and encoding.lower() in ("gzip", "deflate", "br", "zstd"):
```
instead of
```py
if encoding in ("gzip", "deflate", "br", "zstd"):
```
Thank you all. I'll try the whole thing and test it.
Many thanks to @Mattwmaster58 for the pull request. | 2021-08-08T20:01:36 |
mitmproxy/mitmproxy | 4,761 | mitmproxy__mitmproxy-4761 | [
"4751"
] | 92518f3b67c4c91188eb0450012942790dae688f | diff --git a/examples/addons/websocket-inject-message.py b/examples/addons/websocket-inject-message.py
--- a/examples/addons/websocket-inject-message.py
+++ b/examples/addons/websocket-inject-message.py
@@ -13,9 +13,9 @@
def websocket_message(flow: http.HTTPFlow):
assert flow.websocket is not None # make type checker happy
last_message = flow.websocket.messages[-1]
- if b"secret" in last_message.content:
+ if last_message.is_text and "secret" in last_message.text:
last_message.drop()
- ctx.master.commands.call("inject.websocket", flow, last_message.from_client, "ssssssh")
+ ctx.master.commands.call("inject.websocket", flow, last_message.from_client, "ssssssh".encode())
# Complex example: Schedule a periodic timer
@@ -24,7 +24,7 @@ async def inject_async(flow: http.HTTPFlow):
msg = "hello from mitmproxy! "
assert flow.websocket is not None # make type checker happy
while flow.websocket.timestamp_end is None:
- ctx.master.commands.call("inject.websocket", flow, True, msg)
+ ctx.master.commands.call("inject.websocket", flow, True, msg.encode())
await asyncio.sleep(1)
msg = msg[1:] + msg[:1]
| Cannot inject websocket with binary or string content.
#### Problem Description
mitmproxy attempts to parse the injected websocket binary data as text, and replaces the binary data if it cannot be decoded into text, changing the injected websocket message. Also, when a string is given instead, there is error:
File "\mitmproxy\proxy\layers\websocket.py", line 230, in msg
data_str = data.decode(errors="replace")
AttributeError: 'str' object has no attribute 'decode'
#### Steps to reproduce the behavior:
1. from mitmproxy.ctx import master
2. master.commands.call("inject.websocket", flow, False, bytes([i for i in range(256)])) # No error, but message contents are changed
3. master.commands.call("inject.websocket", flow, False, "string") # AttributeError
#### System Information
Mitmproxy: 7.0.2
Python: 3.9.6
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Windows-10-10.0.19043-SP0
| In both cases `bytes` is expected and the last argument `is_text` specifies what type of message you want to inject:
https://github.com/mitmproxy/mitmproxy/blob/ab6f1ebb4415620ce02d61d0ff1c72e6b84b5198/mitmproxy/addons/proxyserver.py#L193
In your first example the bytes are treated as TEXT frame, hence why "mitmproxy attempts to parse the injected websocket binary data as text". In the second example you are passing a string, but utf-8 bytes are expected.
I'm not even sure where this is in the docs, but I'll mark it as a docs issue
The only place where I can find how to inject websocket in the docs is [websocket-inject-message.py example](https://docs.mitmproxy.org/stable/addons-examples/#websocket-inject-message). In the example, the string "ssssssh" is injected, which should result in error.
Yep, this was an oversight here https://github.com/mitmproxy/mitmproxy/pull/4650 The example needs to be fixed.
@Prinzhorn: Would you mind sending a quick PR? ❤️ | 2021-08-17T15:32:12 |
|
mitmproxy/mitmproxy | 4,762 | mitmproxy__mitmproxy-4762 | [
"4742"
] | edbb3d679135af833e09ea8c0c429e6bb0bf0aa0 | diff --git a/mitmproxy/__init__.py b/mitmproxy/__init__.py
--- a/mitmproxy/__init__.py
+++ b/mitmproxy/__init__.py
@@ -1,9 +0,0 @@
-import asyncio
-import sys
-
-if sys.platform == 'win32':
- # workaround for
- # https://github.com/tornadoweb/tornado/issues/2751
- # https://www.tornadoweb.org/en/stable/index.html#installation
- # (copied multiple times in the codebase, please remove all occurrences)
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
| diff --git a/test/mitmproxy/tools/web/test_app.py b/test/mitmproxy/tools/web/test_app.py
--- a/test/mitmproxy/tools/web/test_app.py
+++ b/test/mitmproxy/tools/web/test_app.py
@@ -2,18 +2,10 @@
import json as _json
import logging
import os
-import sys
from unittest import mock
import pytest
-if sys.platform == 'win32':
- # workaround for
- # https://github.com/tornadoweb/tornado/issues/2751
- # https://www.tornadoweb.org/en/stable/index.html#installation
- # (copied multiple times in the codebase, please remove all occurrences)
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
-
import tornado.testing # noqa
from tornado import httpclient # noqa
from tornado import websocket # noqa
| When too many requests come simultaneously, mitmdump called an error and quited [ValueError: too many file descriptors in select()]
#### Problem Description
A clear and concise description of what the bug is.
When too many requests come simultaneously, mitmdump called an error and quited.
Traceback (most recent call last):
File "mitmdump", line 3, in <module>
File "mitmproxy\tools\main.py", line 147, in mitmdump
File "mitmproxy\tools\main.py", line 114, in run
File "mitmproxy\master.py", line 76, in run
File "mitmproxy\master.py", line 59, in run_loop
File "mitmproxy\master.py", line 95, in shutdown
File "asyncio\base_events.py", line 629, in run_until_complete
File "asyncio\base_events.py", line 596, in run_forever
File "asyncio\base_events.py", line 1854, in _run_once
File "selectors.py", line 324, in select
File "selectors.py", line 315, in _select
ValueError: too many file descriptors in select()
[77436] Failed to execute script 'mitmdump' due to unhandled exception!
I googled the error message, and found the following answer. Don't know if it's related.
https://stackoverflow.com/questions/57182009/why-am-i-getting-an-valueerror-too-many-file-descriptors-in-select
#### Steps to reproduce the behavior:
1. I use the following command
`mitmdump.exe -p 8080 --anticomp -q -s "d:\redirect-router.py"`
In the script, I re-write the host for a specific URL
2.
3.
#### System Information
Paste the output of "mitmproxy --version" here.
mitmproxy --version
Mitmproxy: 7.0.2 binary
Python: 3.9.6
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Windows-10-10.0.18363-SP0
| 2021-08-18T14:08:01 |
|
mitmproxy/mitmproxy | 4,772 | mitmproxy__mitmproxy-4772 | [
"4758"
] | 4f925848d9d1551393a3898873d2453e09ca6f25 | diff --git a/mitmproxy/proxy/context.py b/mitmproxy/proxy/context.py
--- a/mitmproxy/proxy/context.py
+++ b/mitmproxy/proxy/context.py
@@ -34,15 +34,10 @@ def fork(self) -> "Context":
return ret
def __repr__(self):
- layers = "\n ".join(repr(l) for l in self.layers)
- if layers:
- layers = f"[\n {layers}\n ]"
- else:
- layers = "[]"
return (
f"Context(\n"
f" {self.client!r},\n"
f" {self.server!r},\n"
- f" layers={layers}\n"
+ f" layers=[{self.layers!r}]\n"
f")"
)
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
@@ -213,8 +213,12 @@ def receive_handshake_data(self, data: bytes) -> layer.CommandGenerator[Tuple[bo
err = last_err[2]
elif last_err == ('SSL routines', 'ssl3_get_record', 'wrong version number') and data[:4].isascii():
err = f"The remote server does not speak TLS."
- else: # pragma: no cover
- # TODO: Add test case once we find one.
+ elif last_err == ('SSL routines', 'ssl3_read_bytes', 'tlsv1 alert protocol version'):
+ err = (
+ f"The remote server and mitmproxy cannot agree on a TLS version to use. "
+ f"You may need to adjust mitmproxy's tls_version_server_min option."
+ )
+ else:
err = f"OpenSSL {e!r}"
self.conn.error = err
return False, err
@@ -428,6 +432,11 @@ def on_handshake_error(self, err: str) -> layer.CommandGenerator[None]:
level: Literal["warn", "info"] = "warn"
if err.startswith("Cannot parse ClientHello"):
pass
+ elif "('SSL routines', 'tls_early_post_process_client_hello', 'unsupported protocol')" in err:
+ err = (
+ f"Client and mitmproxy cannot agree on a TLS version to use. "
+ f"You may need to adjust mitmproxy's tls_version_client_min option."
+ )
elif "unknown ca" in err or "bad certificate" in err:
err = f"The client does not trust the proxy's certificate for {dest} ({err})"
elif err == "connection closed":
| 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
@@ -86,8 +86,13 @@ def test_parse_client_hello():
class SSLTest:
"""Helper container for Python's builtin SSL object."""
- def __init__(self, server_side: bool = False, alpn: typing.Optional[typing.List[str]] = None,
- sni: typing.Optional[bytes] = b"example.mitmproxy.org"):
+ def __init__(
+ self,
+ server_side: bool = False,
+ alpn: typing.Optional[typing.List[str]] = None,
+ sni: typing.Optional[bytes] = b"example.mitmproxy.org",
+ max_ver: typing.Optional[ssl.TLSVersion] = None,
+ ):
self.inc = ssl.MemoryBIO()
self.out = ssl.MemoryBIO()
self.ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER if server_side else ssl.PROTOCOL_TLS_CLIENT)
@@ -104,6 +109,8 @@ def __init__(self, server_side: bool = False, alpn: typing.Optional[typing.List[
certfile=tlsdata.path("../../net/data/verificationcerts/trusted-leaf.crt"),
keyfile=tlsdata.path("../../net/data/verificationcerts/trusted-leaf.key"),
)
+ if max_ver:
+ self.ctx.maximum_version = max_ver
self.obj = self.ctx.wrap_bio(
self.inc,
@@ -162,7 +169,10 @@ def reply_tls_start_client(alpn: typing.Optional[bytes] = None, *args, **kwargs)
"""
def make_client_conn(tls_start: tls.TlsStartData) -> None:
+ # ssl_context = SSL.Context(Method.TLS_METHOD)
+ # ssl_context.set_min_proto_version(SSL.TLS1_3_VERSION)
ssl_context = SSL.Context(SSL.SSLv23_METHOD)
+ ssl_context.set_options(SSL.OP_NO_SSLv3 | SSL.OP_NO_TLSv1 | SSL.OP_NO_TLSv1_1 | SSL.OP_NO_TLSv1_2)
ssl_context.use_privatekey_file(
tlsdata.path("../../net/data/verificationcerts/trusted-leaf.key")
)
@@ -184,7 +194,10 @@ def reply_tls_start_server(alpn: typing.Optional[bytes] = None, *args, **kwargs)
"""
def make_server_conn(tls_start: tls.TlsStartData) -> None:
+ # ssl_context = SSL.Context(Method.TLS_METHOD)
+ # ssl_context.set_min_proto_version(SSL.TLS1_3_VERSION)
ssl_context = SSL.Context(SSL.SSLv23_METHOD)
+ ssl_context.set_options(SSL.OP_NO_SSLv3 | SSL.OP_NO_TLSv1 | SSL.OP_NO_TLSv1_1 | SSL.OP_NO_TLSv1_2)
ssl_context.load_verify_locations(
cafile=tlsdata.path("../../net/data/verificationcerts/trusted-root.crt")
)
@@ -337,6 +350,39 @@ def test_remote_speaks_no_tls(self, tctx):
<< commands.CloseConnection(tctx.server)
)
+ def test_unsupported_protocol(self, tctx: context.Context):
+ """Test the scenario where the server only supports an outdated TLS version by default."""
+ playbook = tutils.Playbook(tls.ServerTLSLayer(tctx))
+ tctx.server.address = ("example.mitmproxy.org", 443)
+ tctx.server.state = ConnectionState.OPEN
+ tctx.server.sni = "example.mitmproxy.org"
+
+ # noinspection PyTypeChecker
+ tssl = SSLTest(server_side=True, max_ver=ssl.TLSVersion.TLSv1_2)
+
+ # send ClientHello
+ data = tutils.Placeholder(bytes)
+ assert (
+ playbook
+ << tls.TlsStartServerHook(tutils.Placeholder())
+ >> reply_tls_start_server()
+ << commands.SendData(tctx.server, data)
+ )
+
+ # receive ServerHello
+ tssl.bio_write(data())
+ with pytest.raises(ssl.SSLError):
+ tssl.do_handshake()
+
+ # send back error
+ assert (
+ playbook
+ >> events.DataReceived(tctx.server, tssl.bio_read())
+ << commands.Log("Server TLS handshake failed. The remote server and mitmproxy cannot agree on a TLS version"
+ " to use. You may need to adjust mitmproxy's tls_version_server_min option.", "warn")
+ << commands.CloseConnection(tctx.server)
+ )
+
def make_client_tls_layer(
tctx: context.Context,
@@ -564,3 +610,20 @@ def test_immediate_disconnect(self, tctx: context.Context, close_at):
"client does not trust the proxy's certificate.", "info")
<< commands.CloseConnection(tctx.client)
)
+
+ def test_unsupported_protocol(self, tctx: context.Context):
+ """Test the scenario where the client only supports an outdated TLS version by default."""
+ playbook, client_layer, tssl_client = make_client_tls_layer(tctx, max_ver=ssl.TLSVersion.TLSv1_2)
+ playbook.logs = True
+
+ assert (
+ playbook
+ >> events.DataReceived(tctx.client, tssl_client.bio_read())
+ << tls.TlsClienthelloHook(tutils.Placeholder())
+ >> tutils.reply()
+ << tls.TlsStartClientHook(tutils.Placeholder())
+ >> reply_tls_start_client()
+ << commands.Log("Client TLS handshake failed. Client and mitmproxy cannot agree on a TLS version to "
+ "use. You may need to adjust mitmproxy's tls_version_client_min option.", "warn")
+ << commands.CloseConnection(tctx.client)
+ )
diff --git a/test/mitmproxy/proxy/tutils.py b/test/mitmproxy/proxy/tutils.py
--- a/test/mitmproxy/proxy/tutils.py
+++ b/test/mitmproxy/proxy/tutils.py
@@ -2,6 +2,7 @@
import difflib
import itertools
import re
+import textwrap
import traceback
import typing
@@ -65,6 +66,7 @@ def _fmt_entry(x: PlaybookEntry):
x = str(x)
x = re.sub('Placeholder:None', '<unset placeholder>', x, flags=re.IGNORECASE)
x = re.sub('Placeholder:', '', x, flags=re.IGNORECASE)
+ x = textwrap.indent(x, " ")[5:]
return f"{arrow} {x}"
| tls_early_post_process_client_hello, unsupported protocol
Mitmproxy: 7.0.2
Python: 3.9.5
OpenSSL: OpenSSL 1.1.1k 25 Mar 2021
Platform: Windows-10-10.0.19043-SP0
```
127.0.0.1:53924: Client TLS handshake failed. The client may not trust the proxy's certificate for www.drumlinsecurity.co.uk (OpenSSL Error([('SSL routines', 'tls_early_post_process_client_hello', 'unsupported protocol')]))
```
but 6.0.2 is ok.
| We need more info to reproduce this. Could you provide a PCAP?
> We need more info to reproduce this. Could you provide a PCAP?
thx.
Can it be sent by email?
Email is on my profile if you have sensitive data in there. :)
Sent mail, please check
Thanks for sending along the PCAP! Can you reproduce this with
```
mitmdump --set tls_version_client_min=SSL3 --set tls_version_server_min=SSL3
```
?
> Thanks for sending along the PCAP! Can you reproduce this with
>
> ```
> mitmdump --set tls_version_client_min=SSL3 --set tls_version_server_min=SSL3
> ```
>
>
Thank you very much.
- mitmdump --set tls_version_client_min=SSL3
After setting it is correct.
I analysis possible that the client only supports ssl3.
- but
set mitmdump --set tls_version_client_**max**=SSL3 --set tls_version_server_min=SSL3
is Fail.
why?
> 127.0.0.1:59879: Unable to establish TLS connection with server (connection closed). Trying to establish TLS with client anyway.

Reset after three handshake
The version order is: SSLv3, TLS 1.0, TLS 1.1, TLS 1.2, TLS 1.3.
Your client only supports TLS 1.0. We had a bug in 7.0.2 which disabled the TLS 1.0 option, so I had to use SSL3, which is one lower. | 2021-08-23T07:10:44 |
mitmproxy/mitmproxy | 4,777 | mitmproxy__mitmproxy-4777 | [
"3506",
"3506"
] | a6f673fb2998790dab22cc67d0fa1905829de1f7 | diff --git a/mitmproxy/log.py b/mitmproxy/log.py
--- a/mitmproxy/log.py
+++ b/mitmproxy/log.py
@@ -1,4 +1,3 @@
-import asyncio
from dataclasses import dataclass
from mitmproxy import hooks
@@ -61,7 +60,7 @@ def error(self, txt):
self(txt, "error")
def __call__(self, text, level="info"):
- asyncio.get_event_loop().call_soon(
+ self.master.event_loop.call_soon_threadsafe(
self.master.addons.trigger, AddLogHook(LogEntry(text, level)),
)
| 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
@@ -40,13 +40,13 @@ async def test_done_writing_failed(self):
def test_add_command(self):
ch = command_history.CommandHistory()
+ with taddons.context(ch):
+ ch.add_command('cmd1')
+ ch.add_command('cmd2')
+ assert ch.history == ['cmd1', 'cmd2']
- ch.add_command('cmd1')
- ch.add_command('cmd2')
- assert ch.history == ['cmd1', 'cmd2']
-
- ch.add_command('')
- assert ch.history == ['cmd1', 'cmd2']
+ ch.add_command('')
+ assert ch.history == ['cmd1', 'cmd2']
@pytest.mark.asyncio
async def test_add_command_failed(self):
| calling `ctx.log` in new thread will raise a RuntimeError exception
##### Steps to reproduce the problem:
1. add an addon for MITMDump
2. start a thread in the addon
3. call `ctx.log.info` in the thread
4. an exception is raised
```
Traceback (most recent call last):
File "/Users/user/.pyenv/versions/3.7.0/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/Users/user/.pyenv/versions/3.7.0/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/Users/user/pro/python/project/project/plugins/crossdomain_xml/__init__.py", line 39, in _check_crossdomain_xml
ctx.log.debug(str(e))
File "/Users/user/pro/python/project/venv/lib/python3.7/site-packages/mitmproxy/log.py", line 29, in debug
self(txt, "debug")
File "/Users/user/pro/python/project/venv/lib/python3.7/site-packages/mitmproxy/log.py", line 59, in __call__
asyncio.get_event_loop().call_soon(
File "/Users/user/.pyenv/versions/3.7.0/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-7'.
```
Except for the main thread, there is no event loop in the other threads, so `asyncio.get_event_loop().call_soon(...)` isn't a good way to send the log message.
##### System information
```
Mitmproxy: 4.0.4
Python: 3.7.0
OpenSSL: OpenSSL 1.1.0i 14 Aug 2018
Platform: Darwin-18.2.0-x86_64-i386-64bit
```
calling `ctx.log` in new thread will raise a RuntimeError exception
##### Steps to reproduce the problem:
1. add an addon for MITMDump
2. start a thread in the addon
3. call `ctx.log.info` in the thread
4. an exception is raised
```
Traceback (most recent call last):
File "/Users/user/.pyenv/versions/3.7.0/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/Users/user/.pyenv/versions/3.7.0/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/Users/user/pro/python/project/project/plugins/crossdomain_xml/__init__.py", line 39, in _check_crossdomain_xml
ctx.log.debug(str(e))
File "/Users/user/pro/python/project/venv/lib/python3.7/site-packages/mitmproxy/log.py", line 29, in debug
self(txt, "debug")
File "/Users/user/pro/python/project/venv/lib/python3.7/site-packages/mitmproxy/log.py", line 59, in __call__
asyncio.get_event_loop().call_soon(
File "/Users/user/.pyenv/versions/3.7.0/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-7'.
```
Except for the main thread, there is no event loop in the other threads, so `asyncio.get_event_loop().call_soon(...)` isn't a good way to send the log message.
##### System information
```
Mitmproxy: 4.0.4
Python: 3.7.0
OpenSSL: OpenSSL 1.1.0i 14 Aug 2018
Platform: Darwin-18.2.0-x86_64-i386-64bit
```
| I am having the same issue, is there any plan to fix this? or a workaround?
I am having the same issue, is there any plan to fix this? or a workaround? | 2021-08-23T17:10:58 |
mitmproxy/mitmproxy | 4,780 | mitmproxy__mitmproxy-4780 | [
"738"
] | c0fd6cfc09068ec0537eea43f6e99f0992d15569 | diff --git a/docs/scripts/api-events.py b/docs/scripts/api-events.py
--- a/docs/scripts/api-events.py
+++ b/docs/scripts/api-events.py
@@ -8,7 +8,7 @@
import mitmproxy.addons.next_layer # noqa
from mitmproxy import hooks, log, addonmanager
from mitmproxy.proxy import server_hooks, layer
-from mitmproxy.proxy.layers import http, tcp, tls, websocket
+from mitmproxy.proxy.layers import http, modes, tcp, tls, websocket
known = set()
@@ -137,6 +137,14 @@ def category(name: str, desc: str, hooks: List[Type[hooks.Hook]]) -> None:
]
)
+ category(
+ "SOCKSv5",
+ "",
+ [
+ modes.Socks5AuthHook,
+ ]
+ )
+
category(
"AdvancedLifecycle",
"",
diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py
--- a/mitmproxy/addons/proxyauth.py
+++ b/mitmproxy/addons/proxyauth.py
@@ -1,5 +1,8 @@
+from __future__ import annotations
+
import binascii
import weakref
+from abc import ABC, abstractmethod
from typing import MutableMapping
from typing import Optional
from typing import Tuple
@@ -7,46 +10,19 @@
import ldap3
import passlib.apache
-from mitmproxy import ctx, connection
+from mitmproxy import connection, ctx
from mitmproxy import exceptions
from mitmproxy import http
from mitmproxy.net.http import status_codes
+from mitmproxy.proxy.layers import modes
REALM = "mitmproxy"
-def mkauth(username: str, password: str, scheme: str = "basic") -> str:
- """
- Craft a basic auth string
- """
- v = binascii.b2a_base64(
- (username + ":" + password).encode("utf8")
- ).decode("ascii")
- return scheme + " " + v
-
-
-def parse_http_basic_auth(s: str) -> Tuple[str, str, str]:
- """
- Parse a basic auth header.
- Raises a ValueError if the input is invalid.
- """
- scheme, authinfo = s.split()
- if scheme.lower() != "basic":
- raise ValueError("Unknown scheme")
- try:
- user, password = binascii.a2b_base64(authinfo.encode()).decode("utf8", "replace").split(":")
- except binascii.Error as e:
- raise ValueError(str(e))
- return scheme, user, password
-
-
class ProxyAuth:
+ validator: Optional[Validator] = None
+
def __init__(self):
- self.nonanonymous = False
- self.htpasswd = None
- self.singleuser = None
- self.ldapconn = None
- self.ldapserver = None
self.authenticated: MutableMapping[connection.Client, Tuple[str, str]] = weakref.WeakKeyDictionary()
"""Contains all connections that are permanently authenticated after an HTTP CONNECT"""
@@ -62,25 +38,73 @@ def load(self, loader):
"""
)
- def enabled(self) -> bool:
- return any([self.nonanonymous, self.htpasswd, self.singleuser, self.ldapconn, self.ldapserver])
+ def configure(self, updated):
+ if "proxyauth" not in updated:
+ return
+ auth = ctx.options.proxyauth
+ if auth:
+ if ctx.options.mode == "transparent":
+ raise exceptions.OptionsError("Proxy Authentication not supported in transparent mode.")
+
+ if auth == "any":
+ self.validator = AcceptAll()
+ elif auth.startswith("@"):
+ self.validator = Htpasswd(auth)
+ elif ctx.options.proxyauth.startswith("ldap"):
+ self.validator = Ldap(auth)
+ elif ":" in ctx.options.proxyauth:
+ self.validator = SingleUser(auth)
+ else:
+ raise exceptions.OptionsError("Invalid proxyauth specification.")
+ else:
+ self.validator = None
+
+ def socks5_auth(self, data: modes.Socks5AuthData) -> None:
+ if self.validator and self.validator(data.username, data.password):
+ data.valid = True
+ self.authenticated[data.client_conn] = data.username, data.password
+
+ def http_connect(self, f: http.HTTPFlow) -> None:
+ if self.validator and self.authenticate_http(f):
+ # Make a note that all further requests over this connection are ok.
+ self.authenticated[f.client_conn] = f.metadata["proxyauth"]
- def is_proxy_auth(self) -> bool:
+ def requestheaders(self, f: http.HTTPFlow) -> None:
+ if self.validator:
+ # Is this connection authenticated by a previous HTTP CONNECT?
+ if f.client_conn in self.authenticated:
+ f.metadata["proxyauth"] = self.authenticated[f.client_conn]
+ else:
+ self.authenticate_http(f)
+
+ def authenticate_http(self, f: http.HTTPFlow) -> bool:
"""
- Returns:
- - True, if authentication is done as if mitmproxy is a proxy
- - False, if authentication is done as if mitmproxy is a HTTP server
+ Authenticate an HTTP request, returns if authentication was successful.
+
+ If valid credentials are found, the matching authentication header is removed.
+ In no or invalid credentials are found, flow.response is set to an error page.
"""
- return ctx.options.mode == "regular" or ctx.options.mode.startswith("upstream:")
+ assert self.validator
+ username = None
+ password = None
+ is_valid = False
+ try:
+ auth_value = f.request.headers.get(self.http_auth_header, "")
+ scheme, username, password = parse_http_basic_auth(auth_value)
+ is_valid = self.validator(username, password)
+ except Exception:
+ pass
- def which_auth_header(self) -> str:
- if self.is_proxy_auth():
- return 'Proxy-Authorization'
+ if is_valid:
+ f.metadata["proxyauth"] = (username, password)
+ del f.request.headers[self.http_auth_header]
+ return True
else:
- return 'Authorization'
+ f.response = self.make_auth_required_response()
+ return False
- def auth_required_response(self) -> http.Response:
- if self.is_proxy_auth():
+ def make_auth_required_response(self) -> http.Response:
+ if self.is_http_proxy:
status_code = status_codes.PROXY_AUTH_REQUIRED
headers = {"Proxy-Authenticate": f'Basic realm="{REALM}"'}
else:
@@ -99,124 +123,120 @@ def auth_required_response(self) -> http.Response:
headers
)
- def check(self, f: http.HTTPFlow) -> Optional[Tuple[str, str]]:
+ @property
+ def http_auth_header(self) -> str:
+ if self.is_http_proxy:
+ return "Proxy-Authorization"
+ else:
+ return "Authorization"
+
+ @property
+ def is_http_proxy(self) -> bool:
"""
- Check if a request is correctly authenticated.
Returns:
- - a (username, password) tuple if successful,
- - None, otherwise.
+ - True, if authentication is done as if mitmproxy is a proxy
+ - False, if authentication is done as if mitmproxy is an HTTP server
"""
- auth_value = f.request.headers.get(self.which_auth_header(), "")
+ return ctx.options.mode == "regular" or ctx.options.mode.startswith("upstream:")
+
+
+def mkauth(username: str, password: str, scheme: str = "basic") -> str:
+ """
+ Craft a basic auth string
+ """
+ v = binascii.b2a_base64(
+ (username + ":" + password).encode("utf8")
+ ).decode("ascii")
+ return scheme + " " + v
+
+
+def parse_http_basic_auth(s: str) -> Tuple[str, str, str]:
+ """
+ Parse a basic auth header.
+ Raises a ValueError if the input is invalid.
+ """
+ scheme, authinfo = s.split()
+ if scheme.lower() != "basic":
+ raise ValueError("Unknown scheme")
+ try:
+ user, password = binascii.a2b_base64(authinfo.encode()).decode("utf8", "replace").split(":")
+ except binascii.Error as e:
+ raise ValueError(str(e))
+ return scheme, user, password
+
+
+class Validator(ABC):
+ """Base class for all username/password validators."""
+
+ @abstractmethod
+ def __call__(self, username: str, password: str) -> bool:
+ raise NotImplementedError
+
+
+class AcceptAll(Validator):
+ def __call__(self, username: str, password: str) -> bool:
+ return True
+
+
+class SingleUser(Validator):
+ def __init__(self, proxyauth: str):
try:
- scheme, username, password = parse_http_basic_auth(auth_value)
+ self.username, self.password = proxyauth.split(':')
except ValueError:
- return None
-
- if self.nonanonymous:
- return username, password
- elif self.singleuser:
- if self.singleuser == [username, password]:
- return username, password
- elif self.htpasswd:
- if self.htpasswd.check_password(username, password):
- return username, password
- elif self.ldapconn:
- if not username or not password:
- return None
- self.ldapconn.search(ctx.options.proxyauth.split(':')[4], '(cn=' + username + ')')
- if self.ldapconn.response:
- conn = ldap3.Connection(
- self.ldapserver,
- self.ldapconn.response[0]['dn'],
- password,
- auto_bind=True)
- if conn:
- return username, password
- return None
-
- def authenticate(self, f: http.HTTPFlow) -> bool:
- valid_credentials = self.check(f)
- if valid_credentials:
- f.metadata["proxyauth"] = valid_credentials
- del f.request.headers[self.which_auth_header()]
- return True
- else:
- f.response = self.auth_required_response()
- return False
+ raise exceptions.OptionsError("Invalid single-user auth specification.")
- # Handlers
- def configure(self, updated):
- if "proxyauth" in updated:
- self.nonanonymous = False
- self.singleuser = None
- self.htpasswd = None
- self.ldapserver = None
- if ctx.options.proxyauth:
- if ctx.options.proxyauth == "any":
- self.nonanonymous = True
- elif ctx.options.proxyauth.startswith("@"):
- p = ctx.options.proxyauth[1:]
- try:
- self.htpasswd = passlib.apache.HtpasswdFile(p)
- except (ValueError, OSError):
- raise exceptions.OptionsError(
- "Could not open htpasswd file: %s" % p
- )
- elif ctx.options.proxyauth.startswith("ldap"):
- parts = ctx.options.proxyauth.split(':')
- if len(parts) != 5:
- raise exceptions.OptionsError(
- "Invalid ldap specification"
- )
- security = parts[0]
- ldap_server = parts[1]
- dn_baseauth = parts[2]
- password_baseauth = parts[3]
- if security == "ldaps":
- server = ldap3.Server(ldap_server, use_ssl=True)
- elif security == "ldap":
- server = ldap3.Server(ldap_server)
- else:
- raise exceptions.OptionsError(
- "Invalid ldap specification on the first part"
- )
- conn = ldap3.Connection(
- server,
- dn_baseauth,
- password_baseauth,
- auto_bind=True)
- self.ldapconn = conn
- self.ldapserver = server
- elif ":" in ctx.options.proxyauth:
- parts = ctx.options.proxyauth.split(':')
- if len(parts) != 2:
- raise exceptions.OptionsError(
- "Invalid single-user auth specification."
- )
- self.singleuser = parts
- else:
- raise exceptions.OptionsError("Invalid proxyauth specification.")
- if self.enabled():
- if ctx.options.mode == "transparent":
- raise exceptions.OptionsError(
- "Proxy Authentication not supported in transparent mode."
- )
- if ctx.options.mode == "socks5":
- raise exceptions.OptionsError(
- "Proxy Authentication not supported in SOCKS mode. "
- "https://github.com/mitmproxy/mitmproxy/issues/738"
- )
- # TODO: check for multiple auth options
+ def __call__(self, username: str, password: str) -> bool:
+ return self.username == username and self.password == password
- def http_connect(self, f: http.HTTPFlow) -> None:
- if self.enabled():
- if self.authenticate(f):
- self.authenticated[f.client_conn] = f.metadata["proxyauth"]
- def requestheaders(self, f: http.HTTPFlow) -> None:
- if self.enabled():
- # Is this connection authenticated by a previous HTTP CONNECT?
- if f.client_conn in self.authenticated:
- f.metadata["proxyauth"] = self.authenticated[f.client_conn]
- return
- self.authenticate(f)
+class Htpasswd(Validator):
+ def __init__(self, proxyauth: str):
+ path = proxyauth[1:]
+ try:
+ self.htpasswd = passlib.apache.HtpasswdFile(path)
+ except (ValueError, OSError):
+ raise exceptions.OptionsError(f"Could not open htpasswd file: {path}")
+
+ def __call__(self, username: str, password: str) -> bool:
+ return self.htpasswd.check_password(username, password)
+
+
+class Ldap(Validator):
+ conn: ldap3.Connection
+ server: ldap3.Server
+ dn_subtree: str
+
+ def __init__(self, proxyauth: str):
+ try:
+ security, url, ldap_user, ldap_pass, self.dn_subtree = proxyauth.split(":")
+ except ValueError:
+ raise exceptions.OptionsError("Invalid ldap specification")
+ if security == "ldaps":
+ server = ldap3.Server(url, use_ssl=True)
+ elif security == "ldap":
+ server = ldap3.Server(url)
+ else:
+ raise exceptions.OptionsError("Invalid ldap specification on the first part")
+ conn = ldap3.Connection(
+ server,
+ ldap_user,
+ ldap_pass,
+ auto_bind=True
+ )
+ self.conn = conn
+ self.server = server
+
+ def __call__(self, username: str, password: str) -> bool:
+ if not username or not password:
+ return False
+ self.conn.search(self.dn_subtree, f"(cn={username})")
+ if self.conn.response:
+ c = ldap3.Connection(
+ self.server,
+ self.conn.response[0]["dn"],
+ password,
+ auto_bind=True
+ )
+ if c:
+ return True
+ return False
diff --git a/mitmproxy/proxy/layers/modes.py b/mitmproxy/proxy/layers/modes.py
--- a/mitmproxy/proxy/layers/modes.py
+++ b/mitmproxy/proxy/layers/modes.py
@@ -1,11 +1,13 @@
import socket
import struct
from abc import ABCMeta
+from dataclasses import dataclass
from typing import Optional
-from mitmproxy import platform
+from mitmproxy import connection, platform
from mitmproxy.net import server_spec
from mitmproxy.proxy import commands, events, layer
+from mitmproxy.proxy.commands import StartHook
from mitmproxy.proxy.layers import tls
from mitmproxy.proxy.utils import expect
@@ -76,6 +78,7 @@ def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]:
SOCKS5_VERSION = 0x05
SOCKS5_METHOD_NO_AUTHENTICATION_REQUIRED = 0x00
+SOCKS5_METHOD_USER_PASSWORD_AUTHENTICATION = 0x02
SOCKS5_METHOD_NO_ACCEPTABLE_METHODS = 0xFF
SOCKS5_ATYP_IPV4_ADDRESS = 0x01
@@ -87,9 +90,26 @@ def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]:
SOCKS5_REP_ADDRESS_TYPE_NOT_SUPPORTED = 0x08
+@dataclass
+class Socks5AuthData:
+ client_conn: connection.Client
+ username: str
+ password: str
+ valid: bool = False
+
+
+@dataclass
+class Socks5AuthHook(StartHook):
+ """
+ Mitmproxy has received username/password SOCKS5 credentials.
+
+ This hook decides whether they are valid by setting `data.valid`.
+ """
+ data: Socks5AuthData
+
+
class Socks5Proxy(DestinationKnown):
buf: bytes = b""
- greeted: bool = False
def socks_err(
self,
@@ -111,92 +131,129 @@ def _handle_event(self, event: events.Event) -> layer.CommandGenerator[None]:
pass
elif isinstance(event, events.DataReceived):
self.buf += event.data
+ yield from self.state()
+ elif isinstance(event, events.ConnectionClosed):
+ if self.buf:
+ yield commands.Log(f"Client closed connection before completing SOCKS5 handshake: {self.buf!r}")
+ yield commands.CloseConnection(event.connection)
+ else:
+ raise AssertionError(f"Unknown event: {event}")
+
+ def state_greet(self):
+ if len(self.buf) < 2:
+ return
- if not self.greeted:
- # Parse Client Greeting
- if len(self.buf) < 2:
- return
-
- if self.buf[0] != SOCKS5_VERSION:
- if self.buf[:3].isupper():
- guess = "Probably not a SOCKS request but a regular HTTP request. "
- else:
- guess = ""
- yield from self.socks_err(guess + "Invalid SOCKS version. Expected 0x05, got 0x%x" % self.buf[0])
- return
-
- n_methods = self.buf[1]
- if len(self.buf) < 2 + n_methods:
- return
- if SOCKS5_METHOD_NO_AUTHENTICATION_REQUIRED not in self.buf[2:2 + n_methods]:
- yield from self.socks_err("mitmproxy only supports SOCKS without authentication",
- SOCKS5_METHOD_NO_ACCEPTABLE_METHODS)
- return
-
- # Send Server Greeting
- # Ver = SOCKS5, Auth = NO_AUTH
- yield commands.SendData(self.context.client, b"\x05\x00")
- self.buf = self.buf[2 + n_methods:]
- self.greeted = True
-
- # Parse Connect Request
- if len(self.buf) < 4:
- return
-
- if self.buf[:3] != b"\x05\x01\x00":
- yield from self.socks_err(f"Unsupported SOCKS5 request: {self.buf!r}", SOCKS5_REP_COMMAND_NOT_SUPPORTED)
- return
-
- # Determine message length
- atyp = self.buf[3]
- message_len: int
- if atyp == SOCKS5_ATYP_IPV4_ADDRESS:
- message_len = 4 + 4 + 2
- elif atyp == SOCKS5_ATYP_IPV6_ADDRESS:
- message_len = 4 + 16 + 2
- elif atyp == SOCKS5_ATYP_DOMAINNAME:
- message_len = 4 + 1 + self.buf[4] + 2
+ if self.buf[0] != SOCKS5_VERSION:
+ if self.buf[:3].isupper():
+ guess = "Probably not a SOCKS request but a regular HTTP request. "
else:
- yield from self.socks_err(f"Unknown address type: {atyp}", SOCKS5_REP_ADDRESS_TYPE_NOT_SUPPORTED)
- return
+ guess = ""
+ yield from self.socks_err(guess + "Invalid SOCKS version. Expected 0x05, got 0x%x" % self.buf[0])
+ return
- # Do we have enough bytes yet?
- if len(self.buf) < message_len:
- return
+ n_methods = self.buf[1]
+ if len(self.buf) < 2 + n_methods:
+ return
- # Parse host and port
- msg, self.buf = self.buf[:message_len], self.buf[message_len:]
+ if "proxyauth" in self.context.options and self.context.options.proxyauth:
+ method = SOCKS5_METHOD_USER_PASSWORD_AUTHENTICATION
+ self.state = self.state_auth
+ else:
+ method = SOCKS5_METHOD_NO_AUTHENTICATION_REQUIRED
+ self.state = self.state_connect
+
+ if method not in self.buf[2:2 + n_methods]:
+ method_str = "user/password" if method == SOCKS5_METHOD_USER_PASSWORD_AUTHENTICATION else "no"
+ yield from self.socks_err(
+ f"Client does not support SOCKS5 with {method_str} authentication.",
+ SOCKS5_METHOD_NO_ACCEPTABLE_METHODS
+ )
+ return
+ yield commands.SendData(self.context.client, bytes([SOCKS5_VERSION, method]))
+ self.buf = self.buf[2 + n_methods:]
+ yield from self.state()
+
+ state = state_greet
+
+ def state_auth(self):
+ if len(self.buf) < 3:
+ return
+
+ # Parsing username and password, which is somewhat atrocious
+ user_len = self.buf[1]
+ if len(self.buf) < 3 + user_len:
+ return
+ pass_len = self.buf[2 + user_len]
+ if len(self.buf) < 3 + user_len + pass_len:
+ return
+ user = self.buf[2:(2 + user_len)].decode("utf-8", "backslashreplace")
+ password = self.buf[(3 + user_len):(3 + user_len + pass_len)].decode("utf-8", "backslashreplace")
+
+ data = Socks5AuthData(self.context.client, user, password)
+ yield Socks5AuthHook(data)
+ if not data.valid:
+ # The VER field contains the current **version of the subnegotiation**, which is X'01'.
+ yield commands.SendData(self.context.client, b"\x01\x01")
+ yield from self.socks_err("authentication failed")
+ return
+
+ yield commands.SendData(self.context.client, b"\x01\x00")
+ self.buf = self.buf[3 + user_len + pass_len:]
+ self.state = self.state_connect
+ yield from self.state()
+
+ def state_connect(self):
+ # Parse Connect Request
+ if len(self.buf) < 4:
+ return
+
+ if self.buf[:3] != b"\x05\x01\x00":
+ yield from self.socks_err(f"Unsupported SOCKS5 request: {self.buf!r}", SOCKS5_REP_COMMAND_NOT_SUPPORTED)
+ return
+
+ # Determine message length
+ atyp = self.buf[3]
+ message_len: int
+ if atyp == SOCKS5_ATYP_IPV4_ADDRESS:
+ message_len = 4 + 4 + 2
+ elif atyp == SOCKS5_ATYP_IPV6_ADDRESS:
+ message_len = 4 + 16 + 2
+ elif atyp == SOCKS5_ATYP_DOMAINNAME:
+ message_len = 4 + 1 + self.buf[4] + 2
+ else:
+ yield from self.socks_err(f"Unknown address type: {atyp}", SOCKS5_REP_ADDRESS_TYPE_NOT_SUPPORTED)
+ return
- host: str
- if atyp == SOCKS5_ATYP_IPV4_ADDRESS:
- host = socket.inet_ntop(socket.AF_INET, msg[4:-2])
- elif atyp == SOCKS5_ATYP_IPV6_ADDRESS:
- host = socket.inet_ntop(socket.AF_INET6, msg[4:-2])
- else:
- host_bytes = msg[5:-2]
- host = host_bytes.decode("ascii", "replace")
+ # Do we have enough bytes yet?
+ if len(self.buf) < message_len:
+ return
- port, = struct.unpack("!H", msg[-2:])
+ # Parse host and port
+ msg, self.buf = self.buf[:message_len], self.buf[message_len:]
- # We now have all we need, let's get going.
- self.context.server.address = (host, port)
- self.child_layer = layer.NextLayer(self.context)
+ host: str
+ if atyp == SOCKS5_ATYP_IPV4_ADDRESS:
+ host = socket.inet_ntop(socket.AF_INET, msg[4:-2])
+ elif atyp == SOCKS5_ATYP_IPV6_ADDRESS:
+ host = socket.inet_ntop(socket.AF_INET6, msg[4:-2])
+ else:
+ host_bytes = msg[5:-2]
+ host = host_bytes.decode("ascii", "replace")
- # this already triggers the child layer's Start event,
- # but that's not a problem in practice...
- err = yield from self.finish_start()
- if err:
- yield commands.SendData(self.context.client, b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00")
- yield commands.CloseConnection(self.context.client)
- else:
- yield commands.SendData(self.context.client, b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")
- if self.buf:
- yield from self.child_layer.handle_event(events.DataReceived(self.context.client, self.buf))
- del self.buf
+ port, = struct.unpack("!H", msg[-2:])
- elif isinstance(event, events.ConnectionClosed):
- if self.buf:
- yield commands.Log(f"Client closed connection before completing SOCKS5 handshake: {self.buf!r}")
- yield commands.CloseConnection(event.connection)
+ # We now have all we need, let's get going.
+ self.context.server.address = (host, port)
+ self.child_layer = layer.NextLayer(self.context)
+
+ # this already triggers the child layer's Start event,
+ # but that's not a problem in practice...
+ err = yield from self.finish_start()
+ if err:
+ yield commands.SendData(self.context.client, b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00")
+ yield commands.CloseConnection(self.context.client)
else:
- raise AssertionError(f"Unknown event: {event}")
+ yield commands.SendData(self.context.client, b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")
+ if self.buf:
+ yield from self.child_layer.handle_event(events.DataReceived(self.context.client, self.buf))
+ del self.buf
| diff --git a/test/mitmproxy/addons/test_proxyauth.py b/test/mitmproxy/addons/test_proxyauth.py
--- a/test/mitmproxy/addons/test_proxyauth.py
+++ b/test/mitmproxy/addons/test_proxyauth.py
@@ -6,6 +6,7 @@
from mitmproxy import exceptions
from mitmproxy.addons import proxyauth
+from mitmproxy.proxy.layers import modes
from mitmproxy.test import taddons
from mitmproxy.test import tflow
@@ -47,89 +48,42 @@ class TestProxyAuth:
('upstream:', True),
('upstream:foobar', True),
])
- def test_is_proxy_auth(self, mode, expected):
+ def test_is_http_proxy(self, mode, expected):
up = proxyauth.ProxyAuth()
with taddons.context(up, loadcore=False) as ctx:
ctx.options.mode = mode
- assert up.is_proxy_auth() is expected
+ assert up.is_http_proxy is expected
- @pytest.mark.parametrize('is_proxy_auth, expected', [
+ @pytest.mark.parametrize('is_http_proxy, expected', [
(True, 'Proxy-Authorization'),
(False, 'Authorization'),
])
- def test_which_auth_header(self, is_proxy_auth, expected):
+ def test_which_auth_header(self, is_http_proxy, expected):
up = proxyauth.ProxyAuth()
- with mock.patch('mitmproxy.addons.proxyauth.ProxyAuth.is_proxy_auth', return_value=is_proxy_auth):
- assert up.which_auth_header() == expected
+ with mock.patch('mitmproxy.addons.proxyauth.ProxyAuth.is_http_proxy', new=is_http_proxy):
+ assert up.http_auth_header == expected
- @pytest.mark.parametrize('is_proxy_auth, expected_status_code, expected_header', [
+ @pytest.mark.parametrize('is_http_proxy, expected_status_code, expected_header', [
(True, 407, 'Proxy-Authenticate'),
(False, 401, 'WWW-Authenticate'),
])
- def test_auth_required_response(self, is_proxy_auth, expected_status_code, expected_header):
+ def test_auth_required_response(self, is_http_proxy, expected_status_code, expected_header):
up = proxyauth.ProxyAuth()
- with mock.patch('mitmproxy.addons.proxyauth.ProxyAuth.is_proxy_auth', return_value=is_proxy_auth):
- resp = up.auth_required_response()
+ with mock.patch('mitmproxy.addons.proxyauth.ProxyAuth.is_http_proxy', new=is_http_proxy):
+ resp = up.make_auth_required_response()
assert resp.status_code == expected_status_code
assert expected_header in resp.headers.keys()
- def test_check(self, tdata):
- up = proxyauth.ProxyAuth()
- with taddons.context(up) as ctx:
- ctx.configure(up, proxyauth="any", mode="regular")
- f = tflow.tflow()
- assert not up.check(f)
- f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
- "test", "test"
- )
- assert up.check(f)
-
- f.request.headers["Proxy-Authorization"] = "invalid"
- assert not up.check(f)
-
- f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
- "test", "test", scheme="unknown"
- )
- assert not up.check(f)
-
- ctx.configure(up, proxyauth="test:test")
- f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
- "test", "test"
- )
- assert up.check(f)
- ctx.configure(up, proxyauth="test:foo")
- assert not up.check(f)
-
- ctx.configure(
- up,
- proxyauth="@" + tdata.path(
- "mitmproxy/net/data/htpasswd"
- )
- )
- f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
- "test", "test"
- )
- assert up.check(f)
- f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
- "test", "foo"
- )
- assert not up.check(f)
-
- with mock.patch('ldap3.Server', return_value="ldap://fake_server:389 - cleartext"):
- with mock.patch('ldap3.Connection', search="test"):
- with mock.patch('ldap3.Connection.search', return_value="test"):
- ctx.configure(
- up,
- proxyauth="ldap:localhost:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com"
- )
- f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
- "test", "test"
- )
- assert up.check(f)
- f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
- "", ""
- )
- assert not up.check(f)
+ def test_socks5(self):
+ pa = proxyauth.ProxyAuth()
+ with taddons.context(pa, loadcore=False) as ctx:
+ ctx.configure(pa, proxyauth="foo:bar", mode="regular")
+ data = modes.Socks5AuthData(tflow.tclient_conn(), "foo", "baz")
+ pa.socks5_auth(data)
+ assert not data.valid
+ data.password = "bar"
+ pa.socks5_auth(data)
+ assert data.valid
def test_authenticate(self):
up = proxyauth.ProxyAuth()
@@ -138,64 +92,60 @@ def test_authenticate(self):
f = tflow.tflow()
assert not f.response
- up.authenticate(f)
+ up.authenticate_http(f)
assert f.response.status_code == 407
f = tflow.tflow()
f.request.headers["Proxy-Authorization"] = proxyauth.mkauth(
"test", "test"
)
- up.authenticate(f)
+ up.authenticate_http(f)
assert not f.response
assert not f.request.headers.get("Proxy-Authorization")
f = tflow.tflow()
ctx.configure(up, mode="reverse")
assert not f.response
- up.authenticate(f)
+ up.authenticate_http(f)
assert f.response.status_code == 401
f = tflow.tflow()
f.request.headers["Authorization"] = proxyauth.mkauth(
"test", "test"
)
- up.authenticate(f)
+ up.authenticate_http(f)
assert not f.response
assert not f.request.headers.get("Authorization")
def test_configure(self, monkeypatch, tdata):
- monkeypatch.setattr(ldap3, "Server", lambda *_, **__: True)
- monkeypatch.setattr(ldap3, "Connection", lambda *_, **__: True)
+ monkeypatch.setattr(ldap3, "Server", mock.MagicMock())
+ monkeypatch.setattr(ldap3, "Connection", mock.MagicMock())
pa = proxyauth.ProxyAuth()
with taddons.context(pa) as ctx:
with pytest.raises(exceptions.OptionsError, match="Invalid proxyauth specification"):
ctx.configure(pa, proxyauth="foo")
- with pytest.raises(exceptions.OptionsError, match="Invalid single-user auth specification."):
- ctx.configure(pa, proxyauth="foo:bar:baz")
-
ctx.configure(pa, proxyauth="foo:bar")
- assert pa.singleuser == ["foo", "bar"]
+ assert isinstance(pa.validator, proxyauth.SingleUser)
+ assert pa.validator("foo", "bar")
+ assert not pa.validator("foo", "baz")
- ctx.configure(pa, proxyauth=None)
- assert pa.singleuser is None
+ with pytest.raises(exceptions.OptionsError, match="Invalid single-user auth specification."):
+ ctx.configure(pa, proxyauth="foo:bar:baz")
ctx.configure(pa, proxyauth="any")
- assert pa.nonanonymous
+ assert isinstance(pa.validator, proxyauth.AcceptAll)
+ assert pa.validator("foo", "bar")
+
ctx.configure(pa, proxyauth=None)
- assert not pa.nonanonymous
+ assert pa.validator is None
ctx.configure(
pa,
proxyauth="ldap:localhost:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com"
)
- assert pa.ldapserver
- ctx.configure(
- pa,
- proxyauth="ldaps:localhost:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com"
- )
- assert pa.ldapserver
+ assert isinstance(pa.validator, proxyauth.Ldap)
with pytest.raises(exceptions.OptionsError, match="Invalid ldap specification"):
ctx.configure(pa, proxyauth="ldap:test:test:test")
@@ -207,30 +157,18 @@ def test_configure(self, monkeypatch, tdata):
ctx.configure(pa, proxyauth="ldapssssssss:fake_server:dn:password:tree")
with pytest.raises(exceptions.OptionsError, match="Could not open htpasswd file"):
- ctx.configure(
- pa,
- proxyauth="@" + tdata.path("mitmproxy/net/data/server.crt")
- )
+ ctx.configure(pa, proxyauth="@" + tdata.path("mitmproxy/net/data/server.crt"))
with pytest.raises(exceptions.OptionsError, match="Could not open htpasswd file"):
ctx.configure(pa, proxyauth="@nonexistent")
- ctx.configure(
- pa,
- proxyauth="@" + tdata.path(
- "mitmproxy/net/data/htpasswd"
- )
- )
- assert pa.htpasswd
- assert pa.htpasswd.check_password("test", "test")
- assert not pa.htpasswd.check_password("test", "foo")
- ctx.configure(pa, proxyauth=None)
- assert not pa.htpasswd
+ ctx.configure(pa, proxyauth="@" + tdata.path("mitmproxy/net/data/htpasswd"))
+ assert isinstance(pa.validator, proxyauth.Htpasswd)
+ assert pa.validator("test", "test")
+ assert not pa.validator("test", "foo")
with pytest.raises(exceptions.OptionsError,
match="Proxy Authentication not supported in transparent mode."):
ctx.configure(pa, proxyauth="any", mode="transparent")
- with pytest.raises(exceptions.OptionsError, match="Proxy Authentication not supported in SOCKS mode."):
- ctx.configure(pa, proxyauth="any", mode="socks5")
def test_handlers(self):
up = proxyauth.ProxyAuth()
@@ -260,3 +198,14 @@ def test_handlers(self):
up.requestheaders(f2)
assert not f2.response
assert f2.metadata["proxyauth"] == ('test', 'test')
+
+
+def test_ldap(monkeypatch):
+ monkeypatch.setattr(ldap3, "Server", mock.MagicMock())
+ monkeypatch.setattr(ldap3, "Connection", mock.MagicMock())
+
+ validator = proxyauth.Ldap("ldaps:localhost:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com")
+ assert not validator("", "")
+ assert validator("foo", "bar")
+ validator.conn.response = False
+ assert not validator("foo", "bar")
diff --git a/test/mitmproxy/proxy/layers/test_modes.py b/test/mitmproxy/proxy/layers/test_modes.py
--- a/test/mitmproxy/proxy/layers/test_modes.py
+++ b/test/mitmproxy/proxy/layers/test_modes.py
@@ -3,6 +3,7 @@
import pytest
from mitmproxy import platform
+from mitmproxy.addons.proxyauth import ProxyAuth
from mitmproxy.connection import Client, Server
from mitmproxy.proxy.commands import CloseConnection, GetSocket, Log, OpenConnection, SendData
from mitmproxy.proxy.context import Context
@@ -316,12 +317,23 @@ def test_socks5_success(address: str, packed: bytes, tctx: Context):
assert nextlayer().data_client() == b"applicationdata"
+def _valid_socks_auth(data: modes.Socks5AuthData):
+ data.valid = True
+
+
def test_socks5_trickle(tctx: Context):
+ ProxyAuth().load(tctx.options)
+ tctx.options.proxyauth = "user:password"
tctx.options.connection_strategy = "lazy"
playbook = Playbook(modes.Socks5Proxy(tctx))
- for x in CLIENT_HELLO:
+ for x in b"\x05\x01\x02":
+ playbook >> DataReceived(tctx.client, bytes([x]))
+ playbook << SendData(tctx.client, b"\x05\x02")
+ for x in b"\x01\x04user\x08password":
playbook >> DataReceived(tctx.client, bytes([x]))
- playbook << SendData(tctx.client, b"\x05\x00")
+ playbook << modes.Socks5AuthHook(Placeholder())
+ playbook >> reply(side_effect=_valid_socks_auth)
+ playbook << SendData(tctx.client, b"\x01\x00")
for x in b"\x05\x01\x00\x01\x7f\x00\x00\x01\x12\x34":
playbook >> DataReceived(tctx.client, bytes([x]))
assert playbook << SendData(tctx.client, b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")
@@ -334,9 +346,6 @@ def test_socks5_trickle(tctx: Context):
(b"abcd",
None,
"Invalid SOCKS version. Expected 0x05, got 0x61"),
- (b"\x05\x01\x02",
- b"\x05\xFF\x00\x01\x00\x00\x00\x00\x00\x00",
- "mitmproxy only supports SOCKS without authentication"),
(CLIENT_HELLO + b"\x05\x02\x00\x01\x7f\x00\x00\x01\x12\x34",
SERVER_HELLO + b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00",
r"Unsupported SOCKS5 request: b'\x05\x02\x00\x01\x7f\x00\x00\x01\x124'"),
@@ -356,6 +365,79 @@ def test_socks5_err(data: bytes, err: bytes, msg: str, tctx: Context):
assert playbook
[email protected]("client_greeting,server_choice,client_auth,server_resp,address,packed", [
+ (b"\x05\x01\x02",
+ b"\x05\x02",
+ b"\x01\x04user\x08password",
+ b"\x01\x00",
+ "127.0.0.1",
+ b"\x01\x7f\x00\x00\x01"),
+ (b"\x05\x02\x01\x02",
+ b"\x05\x02",
+ b"\x01\x04user\x08password",
+ b"\x01\x00",
+ "127.0.0.1",
+ b"\x01\x7f\x00\x00\x01"),
+])
+def test_socks5_auth_success(client_greeting: bytes, server_choice: bytes, client_auth: bytes, server_resp: bytes,
+ address: bytes, packed: bytes, tctx: Context):
+ ProxyAuth().load(tctx.options)
+ tctx.options.proxyauth = "user:password"
+ server = Placeholder(Server)
+ nextlayer = Placeholder(NextLayer)
+ playbook = (
+ Playbook(modes.Socks5Proxy(tctx), logs=True)
+ >> DataReceived(tctx.client, client_greeting)
+ << SendData(tctx.client, server_choice)
+ >> DataReceived(tctx.client, client_auth)
+ << modes.Socks5AuthHook(Placeholder(modes.Socks5AuthData))
+ >> reply(side_effect=_valid_socks_auth)
+ << SendData(tctx.client, server_resp)
+ >> DataReceived(tctx.client, b"\x05\x01\x00" + packed + b"\x12\x34applicationdata")
+ << OpenConnection(server)
+ >> reply(None)
+ << SendData(tctx.client, b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")
+ << NextLayerHook(nextlayer)
+ )
+ assert playbook
+ assert server().address == (address, 0x1234)
+ assert nextlayer().data_client() == b"applicationdata"
+
+
[email protected]("client_greeting,server_choice,client_auth,err,msg", [
+ (b"\x05\x01\x00",
+ None,
+ None,
+ b"\x05\xFF\x00\x01\x00\x00\x00\x00\x00\x00",
+ "Client does not support SOCKS5 with user/password authentication."),
+ (b"\x05\x02\x00\x02",
+ b"\x05\x02",
+ b"\x01\x04" + b"user" + b"\x07" + b"errcode",
+ b"\x01\x01",
+ "authentication failed"),
+])
+def test_socks5_auth_fail(client_greeting: bytes, server_choice: bytes, client_auth: bytes, err: bytes, msg: str,
+ tctx: Context):
+ ProxyAuth().load(tctx.options)
+ tctx.options.proxyauth = "user:password"
+ playbook = (
+ Playbook(modes.Socks5Proxy(tctx), logs=True)
+ >> DataReceived(tctx.client, client_greeting)
+ )
+ if server_choice is None:
+ playbook << SendData(tctx.client, err)
+ else:
+ playbook << SendData(tctx.client, server_choice)
+ playbook >> DataReceived(tctx.client, client_auth)
+ playbook << modes.Socks5AuthHook(Placeholder(modes.Socks5AuthData))
+ playbook >> reply()
+ playbook << SendData(tctx.client, err)
+
+ playbook << CloseConnection(tctx.client)
+ playbook << Log(msg)
+ assert playbook
+
+
def test_socks5_eager_err(tctx: Context):
tctx.options.connection_strategy = "eager"
server = Placeholder(Server)
| Socks Proxy Authentication
I did some quick curl testing, and it seems that with socks mode enabled, single user and no anonymous modes both fail (I didnt have time to test htpasswd mode). If I remove the --socks flag, everything works as expected. I also tried embedding the username and password in the proxy url: `http://test:test@localhost:8080` with the same result.
##### Steps to reproduce the problem:
1. `$ mitmdump --socks --nonanonymous --port 8080`
or
1. `$ mitmdump --socks --singleuser test:test --port 8080`
2. `$ curl -socks5 localhost:8080 --proxy-user test:test http://www.cnn.com`
##### What is the expected behavior?
The http response should have been written to STDOUT.
##### What went wrong?
The actual response was:
`curl: (52) Empty reply from server`
##### Any other comments?
Without the --socks argument mitmdump works fine. I wrote a quick inline script to validate that the authenticator was correctly being set, and call the `test` method on a hardcoded username and password. It looks like the credentials are being sent over and set correctly, but they are not being validated for requests.
```
localhost:8080: clientconnect
{'password_manager': <netlib.http.authentication.PassManSingleUser object at 0x7f19c61fb090>,
'realm': 'mitmproxy'}
{'password': 'test', 'username': 'test'}
True
localhost:8080: Proxy Authentication Required
localhost:8080: clientdisconnect
```
---
mitmdump version: mitmdump 0.13.1
Operating System: Ubuntu/Docker
| Thanks for the excellent report. We're currently rewriting this part of mitmproxy and will revisit this issue once the new parts are in place. :smiley:
SOCKS Proxy Authentication is a feature that is out of scope for us at the moment, but we do welcome external contributions.
Is the issue still open for external contributions?
Yes - we are happy to accept PRs! | 2021-08-25T13:47:32 |
mitmproxy/mitmproxy | 4,845 | mitmproxy__mitmproxy-4845 | [
"4491"
] | 7a6623125399ec1d5b238e1d063162e064a0fa38 | diff --git a/mitmproxy/tools/console/searchable.py b/mitmproxy/tools/console/searchable.py
--- a/mitmproxy/tools/console/searchable.py
+++ b/mitmproxy/tools/console/searchable.py
@@ -19,6 +19,7 @@ class Searchable(urwid.ListBox):
def __init__(self, contents):
self.walker = urwid.SimpleFocusListWalker(contents)
urwid.ListBox.__init__(self, self.walker)
+ self.set_focus(len(self.walker) - 1)
self.search_offset = 0
self.current_highlight = None
self.search_term = None
| WebSocket view jumps to top on new message
The WebSocket view keeps jumping to the top every time a new message arrives. This makes it basically impossible to work with while the connection is open. I hold down arrow -> it scrolls a bit -> message arrives -> I'm back at the top
_Originally posted by @Prinzhorn in https://github.com/mitmproxy/mitmproxy/issues/4486#issuecomment-796578909_
| Hi @mhils how do I reproduce this behaviour? I could have a look into this.
@aaron-tan Open a website with heavy WebSocket traffic, e.g. a twitch stream. When you open the websocket tab you cannot scroll down. Every time a new message arrives it jumps to the top. In the video I'm holding DOWN ARROW. Towards the end of the video I have closed the stream and I can scroll.
https://user-images.githubusercontent.com/679144/131297482-6606c88a-f145-463b-8493-566354758872.mp4
| 2021-10-06T09:31:39 |
|
mitmproxy/mitmproxy | 4,871 | mitmproxy__mitmproxy-4871 | [
"4870"
] | 0ad4a5983e73622d3a25df945084448e86d9c323 | 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
@@ -592,11 +592,11 @@ def handle_connect_finish(self):
)
if 200 <= self.flow.response.status_code < 300:
- yield SendHttp(ResponseHeaders(self.stream_id, self.flow.response, True), self.context.client)
- yield SendHttp(ResponseEndOfMessage(self.stream_id), self.context.client)
self.child_layer = self.child_layer or layer.NextLayer(self.context)
yield from self.child_layer.handle_event(events.Start())
self._handle_event = self.passthrough
+ yield SendHttp(ResponseHeaders(self.stream_id, self.flow.response, True), self.context.client)
+ yield SendHttp(ResponseEndOfMessage(self.stream_id), self.context.client)
else:
yield from self.send_response()
diff --git a/mitmproxy/proxy/layers/http/_http1.py b/mitmproxy/proxy/layers/http/_http1.py
--- a/mitmproxy/proxy/layers/http/_http1.py
+++ b/mitmproxy/proxy/layers/http/_http1.py
@@ -122,7 +122,10 @@ def make_pipe(self) -> layer.CommandGenerator[None]:
self.state = self.passthrough
if self.buf:
already_received = self.buf.maybe_extract_at_most(len(self.buf))
- yield from self.state(events.DataReceived(self.conn, already_received))
+ # Some clients send superfluous newlines after CONNECT, we want to eat those.
+ already_received = already_received.lstrip(b"\r\n")
+ if already_received:
+ yield from self.state(events.DataReceived(self.conn, already_received))
def passthrough(self, event: events.Event) -> layer.CommandGenerator[None]:
assert self.stream_id
| diff --git a/test/mitmproxy/proxy/layers/http/test_http.py b/test/mitmproxy/proxy/layers/http/test_http.py
--- a/test/mitmproxy/proxy/layers/http/test_http.py
+++ b/test/mitmproxy/proxy/layers/http/test_http.py
@@ -1324,3 +1324,23 @@ def make_chunked(flow: HTTPFlow):
b"Transfer-Encoding: chunked\r\n\r\n"
b"0\r\n\r\n")
)
+
+
+def test_connect_more_newlines(tctx):
+ """Ignore superfluous \r\n in CONNECT request, https://github.com/mitmproxy/mitmproxy/issues/4870"""
+ server = Placeholder(Server)
+ playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))
+ nl = Placeholder(layer.NextLayer)
+
+ assert (
+ playbook
+ >> DataReceived(tctx.client, b"CONNECT example.com:80 HTTP/1.1\r\n\r\n\r\n")
+ << http.HttpConnectHook(Placeholder())
+ >> reply()
+ << OpenConnection(server)
+ >> reply(None)
+ << SendData(tctx.client, b'HTTP/1.1 200 Connection established\r\n\r\n')
+ >> DataReceived(tctx.client, b"\x16\x03\x03\x00\xb3\x01\x00\x00\xaf\x03\x03")
+ << layer.NextLayerHook(nl)
+ )
+ assert nl().data_client() == b"\x16\x03\x03\x00\xb3\x01\x00\x00\xaf\x03\x03"
| HttpStream.state_wait_for_request_headers error
#### Problem Description
```
mit_server | 2021-10-19T07:17:01.079759751Z 37.103.81.174:57654: mitmproxy has crashed!
mit_server | 2021-10-19T07:17:01.079788763Z Traceback (most recent call last):
mit_server | 2021-10-19T07:17:01.079794934Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 279, in server_event
mit_server | 2021-10-19T07:17:01.079799991Z for command in layer_commands:
mit_server | 2021-10-19T07:17:01.079804504Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
mit_server | 2021-10-19T07:17:01.079809056Z command = command_generator.send(send)
mit_server | 2021-10-19T07:17:01.079813637Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 255, in handle_event
mit_server | 2021-10-19T07:17:01.079818387Z yield from self._handle(event)
mit_server | 2021-10-19T07:17:01.079826095Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
mit_server | 2021-10-19T07:17:01.079830842Z command = command_generator.send(send)
mit_server | 2021-10-19T07:17:01.079835186Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 740, in _handle_event
mit_server | 2021-10-19T07:17:01.079839927Z yield from self.event_to_child(handler, event)
mit_server | 2021-10-19T07:17:01.079844281Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 761, in event_to_child
mit_server | 2021-10-19T07:17:01.079849161Z yield from self.event_to_child(stream, command.event)
mit_server | 2021-10-19T07:17:01.079853589Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
mit_server | 2021-10-19T07:17:01.079858633Z for command in child.handle_event(event):
mit_server | 2021-10-19T07:17:01.079863297Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
mit_server | 2021-10-19T07:17:01.079902048Z command = command_generator.send(send)
mit_server | 2021-10-19T07:17:01.079906606Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 136, in _handle_event
mit_server | 2021-10-19T07:17:01.079910826Z yield from self.client_state(event)
mit_server | 2021-10-19T07:17:01.079914867Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/utils.py", line 23, in _check_event_type
mit_server | 2021-10-19T07:17:01.079919260Z raise AssertionError(
mit_server | 2021-10-19T07:17:01.079925280Z AssertionError: Unexpected event type at HttpStream.state_wait_for_request_headers: Expected RequestHeaders, got RequestData(stream_id=1, data=b"\x16\x03\x03\x00\xbe\x01\x00\x00\xba\x03\x03anp\xedr'\xd2\xa1\xe5\xf0 9\xf7\r\xef\x9dd/\x8d\xf8r*&K\xf7(\xe8\xd6\xf6\x96\x16\xa3\x00\x00*\xc0,\xc0+\xc00\xc0/\x00\x9f\x00\x9e\xc0$\xc0#\xc0(\xc0'\xc0\n\xc0\t\xc0\x14\xc0\x13\x00\x9d\x00\x9c\x00=\x00<\x005\x00/\x00\n\x01\x00\x00g\x00\x00\x00&\x00$\x00\x00!authentication-prod.ar.indazn.com\x00\n\x00\x08\x00\x06\x00\x1d\x00\x17\x00\x18\x00\x0b\x00\x02\x01\x00\x00\r\x00\x1a\x00\x18\x08\x04\x08\x05\x08\x06\x04\x01\x05\x01\x02\x01\x04\x03\x05\x03\x02\x03\x02\x02\x06\x01\x06\x03\x00#\x00\x00\x00\x17\x00\x00\xff\x01\x00\x01\x00").
mit_server | 2021-10-19T07:17:01.079939109Z
mit_server | 2021-10-19T07:17:04.149705128Z 37.103.81.174:49416: mitmproxy has crashed!
mit_server | 2021-10-19T07:17:04.149733496Z Traceback (most recent call last):
mit_server | 2021-10-19T07:17:04.149738250Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 279, in server_event
mit_server | 2021-10-19T07:17:04.149742511Z for command in layer_commands:
mit_server | 2021-10-19T07:17:04.149746107Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
mit_server | 2021-10-19T07:17:04.149749966Z command = command_generator.send(send)
mit_server | 2021-10-19T07:17:04.149753507Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 255, in handle_event
mit_server | 2021-10-19T07:17:04.149757131Z yield from self._handle(event)
mit_server | 2021-10-19T07:17:04.149760429Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
mit_server | 2021-10-19T07:17:04.149763878Z command = command_generator.send(send)
mit_server | 2021-10-19T07:17:04.149767309Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 740, in _handle_event
mit_server | 2021-10-19T07:17:04.149770905Z yield from self.event_to_child(handler, event)
mit_server | 2021-10-19T07:17:04.149774329Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
mit_server | 2021-10-19T07:17:04.149777989Z for command in child.handle_event(event):
mit_server | 2021-10-19T07:17:04.149781325Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 135, in handle_event
mit_server | 2021-10-19T07:17:04.149784903Z command_generator = self._handle_event(event)
mit_server | 2021-10-19T07:17:04.149788233Z File "/usr/local/lib/python3.9/site-packages/mitmproxy/proxy/utils.py", line 23, in _check_event_type
mit_server | 2021-10-19T07:17:04.149805983Z raise AssertionError(
mit_server | 2021-10-19T07:17:04.149809318Z AssertionError: Unexpected event type at HttpStream._handle_event: Expected Start|HttpEvent, got ConnectionClosed(connection=Server({'id': '…a2bdcc', 'address': ('api-global.netflix.com', 443), 'state': <ConnectionState.CAN_WRITE: 2>, 'timestamp_start': 1634627762.836605, 'timestamp_tcp_setup': 1634627763.5006588, 'peername': ('34.214.223.171', 443), 'sockname': ('172.23.0.4', 57018)})).
```
#### Steps to reproduce the behavior:
1. After a period of use, the client shuts down the proxy and the server keeps printing error messages
2.The client is iphone
#### System Information
Mitmproxy: 7.0.4
Python: 3.9.7
OpenSSL: OpenSSL 1.1.1l 24 Aug 2021
Platform: Linux-3.10.0-1127.18.2.el7.x86_64-x86_64-with-glibc2.28
| Thanks! How hard is this to reproduce? Could you reproduce it with `--set proxy_debug` and send me the corresponding log either here or by email?
Thanks for your reply, this is my log,Because the log is too large, I only intercepted part of it
------------------ 原始邮件 ------------------
发件人: "mitmproxy/mitmproxy" ***@***.***>;
发送时间: 2021年10月19日(星期二) 下午3:50
***@***.***>;
***@***.******@***.***>;
主题: Re: [mitmproxy/mitmproxy] HttpStream.state_wait_for_request_headers error (Issue #4870)
Thanks! How hard is this to reproduce? Could you reproduce it with --set proxy_debug and send me the corresponding log either here or by email?
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub, or unsubscribe.
Triage notifications on the go with GitHub Mobile for iOS or Android.
Thanks for your reply, this is my log,Because the log is too large, I only intercepted part of it
[mitm.log](https://github.com/mitmproxy/mitmproxy/files/7371894/mitm.log)
| 2021-10-19T11:21:30 |
mitmproxy/mitmproxy | 4,882 | mitmproxy__mitmproxy-4882 | [
"4876"
] | 1c10abef000ba2f112bc00119bcdb6707d6ff08e | diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py
--- a/mitmproxy/addons/clientplayback.py
+++ b/mitmproxy/addons/clientplayback.py
@@ -78,7 +78,10 @@ def __init__(self, flow: http.HTTPFlow, options: Options) -> None:
super().__init__(context)
- self.layer = layers.HttpLayer(context, HTTPMode.transparent)
+ if options.mode.startswith("upstream:"):
+ self.layer = layers.HttpLayer(context, HTTPMode.upstream)
+ else:
+ self.layer = layers.HttpLayer(context, HTTPMode.transparent)
self.layer.connections[client] = MockServer(flow, context.fork())
self.flow = flow
self.done = asyncio.Event()
| diff --git a/test/mitmproxy/addons/test_clientplayback.py b/test/mitmproxy/addons/test_clientplayback.py
--- a/test/mitmproxy/addons/test_clientplayback.py
+++ b/test/mitmproxy/addons/test_clientplayback.py
@@ -31,13 +31,13 @@ async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
writer.close()
handler_ok.set()
return
+ req = await reader.readline()
if mode == "upstream":
- conn_req = await reader.readuntil(b"\r\n\r\n")
- assert conn_req == b'CONNECT address:22 HTTP/1.1\r\n\r\n'
- writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
+ assert req == b'GET http://address:22/path HTTP/1.1\r\n'
+ else:
+ assert req == b'GET /path HTTP/1.1\r\n'
req = await reader.readuntil(b"data")
assert req == (
- b'GET /path HTTP/1.1\r\n'
b'header: qvalue\r\n'
b'content-length: 4\r\n'
b'\r\n'
@@ -59,6 +59,8 @@ async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
flow.request.content = b"data"
if mode == "upstream":
tctx.options.mode = f"upstream:http://{addr[0]}:{addr[1]}"
+ flow.request.authority = f"{addr[0]}:{addr[1]}"
+ flow.request.host, flow.request.port = 'address', 22
else:
flow.request.host, flow.request.port = addr
cp.start_replay([flow])
@@ -70,6 +72,37 @@ async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
assert flow.response.status_code == 204
[email protected]
+async def test_playback_https_upstream():
+ handler_ok = asyncio.Event()
+
+ async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
+ conn_req = await reader.readuntil(b"\r\n\r\n")
+ assert conn_req == b'CONNECT address:22 HTTP/1.1\r\n\r\n'
+ writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
+ await writer.drain()
+ assert not await reader.read()
+ handler_ok.set()
+
+ cp = ClientPlayback()
+ ps = Proxyserver()
+ with taddons.context(cp, ps) as tctx:
+ tctx.configure(cp)
+ async with tcp_server(handler) as addr:
+ cp.running()
+ flow = tflow.tflow()
+ flow.request.scheme = b"https"
+ flow.request.content = b"data"
+ tctx.options.mode = f"upstream:http://{addr[0]}:{addr[1]}"
+ cp.start_replay([flow])
+ assert cp.count() == 1
+ await asyncio.wait_for(cp.queue.join(), 5)
+ await asyncio.wait_for(handler_ok.wait(), 5)
+ cp.done()
+ assert flow.response is None
+ assert str(flow.error) == f'Upstream proxy {addr[0]}:{addr[1]} refused HTTP CONNECT request: 502 Bad Gateway'
+
+
@pytest.mark.asyncio
async def test_playback_crash(monkeypatch):
async def raise_err():
| Replay via upstream proxy uses CONNECT instead of original request method for HTTP connections
#### Problem Description
Replaying a request that was routed through a upstream proxy server fails as the preceding CONNECT method is not supported.
#### Steps to reproduce the behavior:
1. Run mitmpoxy in upstream mode (e.g. route traffic through tinyproxy server)
2. Execute any request
3. Replay this request
4. The replay fails as it is executed with a preceding CONNECT request
#### System Information
Mitmproxy: 8.0.0.dev (+148, commit 79f464b)
Python: 3.8.10
OpenSSL: OpenSSL 1.1.1l 24 Aug 2021
Platform: Linux-5.11.0-38-generic-x86_64-with-glibc2.29
| This needs concrete repro steps. The following setup creates two perfectly replayable requests for me:
```
mitmproxy -p 8001
```
```
mitmproxy --mode upstream:localhost:8001 --set ssl_insecure
```
```
curl -x localhost:8080 -k https://example.com http://example.com
```
My setup is practically equal to yours, except I use `tinyproxy` as proxy. The original request works like a charm, replay fails with "Upstream proxy 127.0.0.1:8001 refused HTTP CONNECT request: 403 Access violation".
Might be also be a tinyproxy bug but the CONNECT method is not required to replay the original request.
Ah, I see. Can you confirm that this only applies to plaintext http:// requests? For HTTPS you do need `CONNECT`. In this case what we are doing is not wrong per se, but I agree that it would be nicer to proxy absolute-form HTTP requests and not `CONNECT` before that.
Yes, I can confirm, that this only applies for raw HTTP.
With HTTPS it works.
Thanks. The problem here likely is the interaction between replaying in transparent mode:
https://github.com/mitmproxy/mitmproxy/blob/1c10abef000ba2f112bc00119bcdb6707d6ff08e/mitmproxy/addons/clientplayback.py#L81
while checking whether we need to CONNECT here:
https://github.com/mitmproxy/mitmproxy/blob/1c10abef000ba2f112bc00119bcdb6707d6ff08e/mitmproxy/proxy/layers/http/__init__.py#L834
I think we need to be smarter about setting the HTTP mode for client replay, it may just be good enough to set this to upstream when we are in upstream mode. I won't find any time to work on this anytime soon, but if you want to take a closer look I'd be happy to merge a PR. | 2021-10-27T08:56:24 |
mitmproxy/mitmproxy | 4,905 | mitmproxy__mitmproxy-4905 | [
"4902"
] | 83f05897ce57dad5c98d787d23dc87ca4b0a663c | diff --git a/mitmproxy/tools/console/commandexecutor.py b/mitmproxy/tools/console/commandexecutor.py
--- a/mitmproxy/tools/console/commandexecutor.py
+++ b/mitmproxy/tools/console/commandexecutor.py
@@ -19,7 +19,7 @@ def __call__(self, cmd):
except exceptions.CommandError as e:
ctx.log.error(str(e))
else:
- if ret:
+ if ret is not None:
if type(ret) == typing.Sequence[flow.Flow]:
signals.status_message.send(
message="Command returned %s flows" % len(ret)
diff --git a/mitmproxy/tools/console/grideditor/editors.py b/mitmproxy/tools/console/grideditor/editors.py
--- a/mitmproxy/tools/console/grideditor/editors.py
+++ b/mitmproxy/tools/console/grideditor/editors.py
@@ -213,11 +213,11 @@ def __init__(
vals: typing.Union[
typing.List[typing.List[typing.Any]],
typing.List[typing.Any],
- str,
+ typing.Any,
]) -> None:
- if vals:
+ if vals is not None:
# Whatever vals is, make it a list of rows containing lists of column values.
- if isinstance(vals, str):
+ if not isinstance(vals, list):
vals = [vals]
if not isinstance(vals[0], list):
vals = [[i] for i in vals]
| diff --git a/test/mitmproxy/tools/console/test_integration.py b/test/mitmproxy/tools/console/test_integration.py
--- a/test/mitmproxy/tools/console/test_integration.py
+++ b/test/mitmproxy/tools/console/test_integration.py
@@ -54,3 +54,8 @@ def test_options_home_end(console):
@pytest.mark.asyncio
def test_keybindings_home_end(console):
console.type("K<home><end>")
+
+
[email protected]
+def test_replay_count(console):
+ console.type(":replay.server.count<enter>")
| Crash when invoking replay.server.count from console
#### Problem Description
Invoking `replay.server.count` from the console causes a crash. I don't think it happens all the time, but see below for repeatable reproduction.
#### Steps to reproduce the behavior:
1. Start `mitmproxy`
2. Hit `n` to create a new flow
3. Hit Enter
4. Hit `r` to issue the request
5. With the same flow selected, issue the command `:replay.server @focus`
6. Issue the command `:replay.server.count`
Sample stack trace:
```python
File "/home/elespike/venvs/mitmproxy/lib/python3.9/site-packages/mitmproxy/tools/console/grideditor/editors.py", line 222, in __init__
if not isinstance(vals[0], list):
TypeError: 'int' object is not subscriptable
```
#### System Information
```
Mitmproxy: 7.0.4
Python: 3.9.2
```
| 2021-11-17T06:39:41 |
|
mitmproxy/mitmproxy | 4,909 | mitmproxy__mitmproxy-4909 | [
"4902"
] | 39fa242e25ad6d879e7021db188d0d32f4d77115 | diff --git a/mitmproxy/addons/dumper.py b/mitmproxy/addons/dumper.py
--- a/mitmproxy/addons/dumper.py
+++ b/mitmproxy/addons/dumper.py
@@ -38,10 +38,10 @@ def load(self, loader):
loader.add_option(
"flow_detail", int, 1,
"""
- The display detail level for flows in mitmdump: 0 (almost quiet) to 3 (very verbose).
- 0: shortened request URL, response status code, WebSocket and TCP message notifications.
- 1: full request URL with response status code
- 2: 1 + HTTP headers
+ The display detail level for flows in mitmdump: 0 (quiet) to 4 (very verbose).
+ 0: no output
+ 1: shortened request URL with response status code
+ 2: full request URL with response status code and HTTP headers
3: 2 + truncated response content, content of WebSocket and TCP messages
4: 3 + nothing is truncated
"""
@@ -156,7 +156,7 @@ def _echo_request_line(self, flow: http.HTTPFlow) -> None:
else:
url = flow.request.url
- if ctx.options.flow_detail <= 1:
+ if ctx.options.flow_detail == 1:
# We need to truncate before applying styles, so we just focus on the URL.
terminal_width_limit = max(shutil.get_terminal_size()[0] - 25, 50)
if len(url) > terminal_width_limit:
| diff --git a/test/mitmproxy/addons/test_dumper.py b/test/mitmproxy/addons/test_dumper.py
--- a/test/mitmproxy/addons/test_dumper.py
+++ b/test/mitmproxy/addons/test_dumper.py
@@ -158,7 +158,7 @@ def test_echo_request_line():
assert "nonstandard" in sio.getvalue()
sio.truncate(0)
- ctx.configure(d, flow_detail=0, showhost=True)
+ ctx.configure(d, flow_detail=1, showhost=True)
f = tflow.tflow(resp=True)
terminalWidth = max(shutil.get_terminal_size()[0] - 25, 50)
f.request.url = "http://address:22/" + ("x" * terminalWidth) + "textToBeTruncated"
| Crash when invoking replay.server.count from console
#### Problem Description
Invoking `replay.server.count` from the console causes a crash. I don't think it happens all the time, but see below for repeatable reproduction.
#### Steps to reproduce the behavior:
1. Start `mitmproxy`
2. Hit `n` to create a new flow
3. Hit Enter
4. Hit `r` to issue the request
5. With the same flow selected, issue the command `:replay.server @focus`
6. Issue the command `:replay.server.count`
Sample stack trace:
```python
File "/home/elespike/venvs/mitmproxy/lib/python3.9/site-packages/mitmproxy/tools/console/grideditor/editors.py", line 222, in __init__
if not isinstance(vals[0], list):
TypeError: 'int' object is not subscriptable
```
#### System Information
```
Mitmproxy: 7.0.4
Python: 3.9.2
```
| 2021-11-17T18:40:24 |
|
mitmproxy/mitmproxy | 4,910 | mitmproxy__mitmproxy-4910 | [
"4902"
] | 39fa242e25ad6d879e7021db188d0d32f4d77115 | diff --git a/mitmproxy/types.py b/mitmproxy/types.py
--- a/mitmproxy/types.py
+++ b/mitmproxy/types.py
@@ -369,7 +369,7 @@ class _FlowType(_BaseFlowType):
def parse(self, manager: "CommandManager", t: type, s: str) -> flow.Flow:
try:
- flows = manager.execute("view.flows.resolve %s" % (s))
+ flows = manager.call_strings("view.flows.resolve", [s])
except exceptions.CommandError as e:
raise exceptions.TypeError(str(e)) from e
if len(flows) != 1:
@@ -388,7 +388,7 @@ class _FlowsType(_BaseFlowType):
def parse(self, manager: "CommandManager", t: type, s: str) -> typing.Sequence[flow.Flow]:
try:
- return manager.execute("view.flows.resolve %s" % (s))
+ return manager.call_strings("view.flows.resolve", [s])
except exceptions.CommandError as e:
raise exceptions.TypeError(str(e)) from e
| 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
@@ -183,7 +183,10 @@ class DummyConsole:
def resolve(self, spec: str) -> typing.Sequence[flow.Flow]:
if spec == "err":
raise mitmproxy.exceptions.CommandError()
- n = int(spec)
+ try:
+ n = int(spec)
+ except ValueError:
+ n = 1
return [tflow.tflow(resp=True)] * n
@command.command("cut")
@@ -201,6 +204,7 @@ def test_flow():
b = mitmproxy.types._FlowType()
assert len(b.completion(tctx.master.commands, flow.Flow, "")) == len(b.valid_prefixes)
assert b.parse(tctx.master.commands, flow.Flow, "1")
+ assert b.parse(tctx.master.commands, flow.Flow, "has space")
assert b.is_valid(tctx.master.commands, flow.Flow, tflow.tflow()) is True
assert b.is_valid(tctx.master.commands, flow.Flow, "xx") is False
with pytest.raises(mitmproxy.exceptions.TypeError):
@@ -224,6 +228,7 @@ def test_flows():
assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "0")) == 0
assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "1")) == 1
assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "2")) == 2
+ assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "has space")) == 1
with pytest.raises(mitmproxy.exceptions.TypeError):
b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "err")
| Crash when invoking replay.server.count from console
#### Problem Description
Invoking `replay.server.count` from the console causes a crash. I don't think it happens all the time, but see below for repeatable reproduction.
#### Steps to reproduce the behavior:
1. Start `mitmproxy`
2. Hit `n` to create a new flow
3. Hit Enter
4. Hit `r` to issue the request
5. With the same flow selected, issue the command `:replay.server @focus`
6. Issue the command `:replay.server.count`
Sample stack trace:
```python
File "/home/elespike/venvs/mitmproxy/lib/python3.9/site-packages/mitmproxy/tools/console/grideditor/editors.py", line 222, in __init__
if not isinstance(vals[0], list):
TypeError: 'int' object is not subscriptable
```
#### System Information
```
Mitmproxy: 7.0.4
Python: 3.9.2
```
| 2021-11-18T00:36:00 |
|
mitmproxy/mitmproxy | 4,911 | mitmproxy__mitmproxy-4911 | [
"4908"
] | 888ce66f902add53d7fcbb2df44ed010229098fd | diff --git a/mitmproxy/contrib/urwid/raw_display.py b/mitmproxy/contrib/urwid/raw_display.py
--- a/mitmproxy/contrib/urwid/raw_display.py
+++ b/mitmproxy/contrib/urwid/raw_display.py
@@ -260,7 +260,9 @@ def _start(self, alternate_buffer=True):
)
ok = win32.SetConsoleMode(hOut, dwOutMode)
- assert ok
+ if not ok:
+ raise RuntimeError("Error enabling virtual terminal processing, "
+ "mitmproxy's console interface requires Windows 10 Build 10586 or above.")
ok = win32.SetConsoleMode(hIn, dwInMode)
assert ok
else:
| RuntimeWarning: coroutine 'BaseEventLoop._create_server_getaddrinfo' was never awaited
#### Problem Description
I get this error when i run the mitmproxy command
```
Traceback (most recent call last):
File "mitmproxy\master.py", line 54, in run_loop
File "urwid\main_loop.py", line 287, in run
File "urwid\main_loop.py", line 377, in _run
File "urwid\main_loop.py", line 338, in start
File "urwid\display_common.py", line 813, in start
File "mitmproxy\contrib\urwid\raw_display.py", line 263, in _start
AssertionError
mitmproxy has crashed!
Please lodge a bug report at:
https://github.com/mitmproxy/mitmproxy/issues
7[?47hsys:1: RuntimeWarning: coroutine 'BaseEventLoop._create_server_getaddrinfo' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
```
#### Steps to reproduce the behavior:
1. Open CMD on windows and run mitmproxy
#### System Information
Mitmproxy: 7.0.4 binary
Python: 3.9.7
OpenSSL: OpenSSL 1.1.1l 24 Aug 2021
Platform: Windows-10-10.0.10240-SP0
| How do you run the mitmproxy command? In other words, which console are you using? cmd, powershell, something else?
> How do you run the mitmproxy command? In other words, which console are you using? cmd, powershell, something else?
I am using CMD. I can't install windows terminal (my windows version is lower)
Which Windows version are you on? :)
Windows-10 build 1024
Thanks for confirming. mitmproxy's console interface won't work before build 10586, which I think is the first build that includes ENABLE_VIRTUAL_TERMINAL_PROCESSING. mitmweb and mitmdump should be fine. I'll make sure that we have a better error message here. | 2021-11-18T07:41:33 |
|
mitmproxy/mitmproxy | 4,919 | mitmproxy__mitmproxy-4919 | [
"4918"
] | 9a469806eb6a202f5b35c011368fd240a16f5397 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -86,6 +86,8 @@
"pyparsing>=2.4.2,<2.5",
"pyperclip>=1.6.0,<1.9",
"ruamel.yaml>=0.16,<0.17.17",
+ # Kaitai parsers depend on setuptools, remove once https://github.com/kaitai-io/kaitai_struct_python_runtime/issues/62 is fixed
+ "setuptools",
"sortedcontainers>=2.3,<2.5",
"tornado>=6.1,<7",
"urwid>=2.1.1,<2.2",
| mitmproxy depends on `pkg_resources` at runtime but does not specify `install_requires=setuptools`
#### Problem Description
A clear and concise description of what the bug is.
https://github.com/mitmproxy/mitmproxy/blob/0ca458fd6475ee48728147f3b529467a75e912a4/mitmproxy/contrib/kaitaistruct/exif.py#L7
the `pkg_resources` module is provided by `setuptools`
installation into a minimal environment (for example, bazel) will break without also needing to specify `setuptools`
mitmproxy should depend on `setuptools`
#### Steps to reproduce the behavior:
1. simulate a minimal environment:
```
virtualenv venv
venv/bin/pip install mitmproxy
venv/bin/pip uninstall setuptools
venv/bin/pip install mitmproxy # make sure we actually have its deps even after uninstalling
```
2. run `mitmproxy --help`
```console
$ venv/bin/mitmproxy --help
Traceback (most recent call last):
File "venv/bin/mitmproxy", line 5, in <module>
from mitmproxy.tools.main import mitmproxy
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/tools/main.py", line 8, in <module>
from mitmproxy import exceptions, master
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/master.py", line 10, in <module>
from mitmproxy import eventsequence
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/eventsequence.py", line 8, in <module>
from mitmproxy.proxy import layers
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/proxy/layers/__init__.py", line 1, in <module>
from . import modes
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/proxy/layers/modes.py", line 9, in <module>
from mitmproxy.proxy.layers import tls
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/proxy/layers/tls.py", line 8, in <module>
from mitmproxy.net import tls as net_tls
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/net/tls.py", line 18, in <module>
from mitmproxy.contrib.kaitaistruct import tls_client_hello
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/contrib/kaitaistruct/tls_client_hello.py", line 7, in <module>
from pkg_resources import parse_version
ModuleNotFoundError: No module named 'pkg_resources'
```
#### System Information
Paste the output of "mitmproxy --version" here.
```console
$ venv/bin/mitmproxy --version
Traceback (most recent call last):
File "venv/bin/mitmproxy", line 5, in <module>
from mitmproxy.tools.main import mitmproxy
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/tools/main.py", line 8, in <module>
from mitmproxy import exceptions, master
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/master.py", line 10, in <module>
from mitmproxy import eventsequence
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/eventsequence.py", line 8, in <module>
from mitmproxy.proxy import layers
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/proxy/layers/__init__.py", line 1, in <module>
from . import modes
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/proxy/layers/modes.py", line 9, in <module>
from mitmproxy.proxy.layers import tls
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/proxy/layers/tls.py", line 8, in <module>
from mitmproxy.net import tls as net_tls
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/net/tls.py", line 18, in <module>
from mitmproxy.contrib.kaitaistruct import tls_client_hello
File "/tmp/y/venv/lib/python3.8/site-packages/mitmproxy/contrib/kaitaistruct/tls_client_hello.py", line 7, in <module>
from pkg_resources import parse_version
ModuleNotFoundError: No module named 'pkg_resources'
```
| 2021-11-19T20:36:33 |
||
mitmproxy/mitmproxy | 4,932 | mitmproxy__mitmproxy-4932 | [
"4931"
] | 1c93a9369683b1d6f978d4cbee7e528f58ca8b09 | diff --git a/mitmproxy/proxy/layers/websocket.py b/mitmproxy/proxy/layers/websocket.py
--- a/mitmproxy/proxy/layers/websocket.py
+++ b/mitmproxy/proxy/layers/websocket.py
@@ -86,7 +86,6 @@ class WebsocketLayer(layer.Layer):
def __init__(self, context: Context, flow: http.HTTPFlow):
super().__init__(context)
self.flow = flow
- assert context.server.connected
@expect(events.Start)
def start(self, _) -> layer.CommandGenerator[None]:
| Event type error says mitmproxy has crashed without actually crashing
#### Problem Description
Some sort of event type error...? This happened when I was testing `modify_body` and `modify_headers` options (see reproduction steps) and it results in repeated error messages with really long tracebacks.
The error messages begin by saying that mitmproxy has crashed, but it doesn't actually crash.
```
[... lots more traceback before the below]
File "/home/elespike/venvs/mitmproxy/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, inhandle_event
command = command_generator.send(send)
File
"/home/elespike/venvs/mitmproxy/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line136, in _handle_event
yield from self.client_state(event)
File "/home/elespike/venvs/mitmproxy/lib/python3.9/site-packages/mitmproxy/proxy/utils.py", line 23, in
_check_event_type
raise AssertionError(
AssertionError: Unexpected event type at HttpStream.state_done: Expected no events, got
RequestEndOfMessage(stream_id=1).
```
#### Steps to reproduce the behavior:
1. Start with default options
2. Set `modify_body` and `modify_headers` as follows:
```
modify_body:
- :~u webhook.site ~q::<h1>hey</h1>
modify_headers:
- :~u webhook.site ~s:content-type:text/html
```
3. Visit https://webhook.site
#### System Information
Mitmproxy: 7.0.4
Python: 3.9.2
| 2021-11-21T15:35:09 |
||
mitmproxy/mitmproxy | 4,964 | mitmproxy__mitmproxy-4964 | [
"3584",
"3584"
] | 3a2c87432c927226494064436087ddb779612f82 | diff --git a/mitmproxy/addons/script.py b/mitmproxy/addons/script.py
--- a/mitmproxy/addons/script.py
+++ b/mitmproxy/addons/script.py
@@ -75,6 +75,7 @@ def __init__(self, path: str, reload: bool) -> None:
path.strip("'\" ")
)
self.ns = None
+ self.is_running = False
if not os.path.isfile(self.fullpath):
raise exceptions.OptionsError('No such script')
@@ -85,6 +86,9 @@ def __init__(self, path: str, reload: bool) -> None:
else:
self.loadscript()
+ def running(self):
+ self.is_running = True
+
def done(self):
if self.reloadtask:
self.reloadtask.cancel()
@@ -105,7 +109,8 @@ def loadscript(self):
if self.ns:
# We're already running, so we have to explicitly register and
# configure the addon
- ctx.master.addons.invoke_addon(self.ns, hooks.RunningHook())
+ if self.is_running:
+ ctx.master.addons.invoke_addon(self.ns, hooks.RunningHook())
try:
ctx.master.addons.invoke_addon(
self.ns,
| diff --git a/test/mitmproxy/addons/test_script.py b/test/mitmproxy/addons/test_script.py
--- a/test/mitmproxy/addons/test_script.py
+++ b/test/mitmproxy/addons/test_script.py
@@ -1,5 +1,6 @@
import asyncio
import os
+import re
import sys
import traceback
@@ -11,6 +12,7 @@
from mitmproxy.proxy.layers.http import HttpRequestHook
from mitmproxy.test import taddons
from mitmproxy.test import tflow
+from mitmproxy.tools import main
# We want this to be speedy for testing
@@ -90,7 +92,7 @@ async def test_simple(self, tdata):
)
with taddons.context(sc) as tctx:
tctx.configure(sc)
- await tctx.master.await_log("recorder running")
+ await tctx.master.await_log("recorder configure")
rec = tctx.master.addons.get("recorder")
assert rec.call_log[0][0:2] == ("recorder", "load")
@@ -128,7 +130,7 @@ async def test_exception(self, tdata):
True,
)
tctx.master.addons.add(sc)
- await tctx.master.await_log("error running")
+ await tctx.master.await_log("error load")
tctx.configure(sc)
f = tflow.tflow(resp=True)
@@ -331,3 +333,21 @@ async def test_order(self, tdata):
'e running',
'e configure',
]
+
+
+def test_order(event_loop, tdata, capsys):
+ """Integration test: Make sure that the runtime hooks are triggered on startup in the correct order."""
+ asyncio.set_event_loop(event_loop)
+ main.mitmdump([
+ "-n",
+ "-s", tdata.path("mitmproxy/data/addonscripts/recorder/recorder.py"),
+ "-s", tdata.path("mitmproxy/data/addonscripts/shutdown.py"),
+ ])
+ assert re.match(
+ r"Loading script.+recorder.py\n"
+ r"\('recorder', 'load', .+\n"
+ r"\('recorder', 'configure', .+\n"
+ r"Loading script.+shutdown.py\n"
+ r"\('recorder', 'running', .+\n$",
+ capsys.readouterr().out,
+ )
diff --git a/test/mitmproxy/data/addonscripts/error.py b/test/mitmproxy/data/addonscripts/error.py
--- a/test/mitmproxy/data/addonscripts/error.py
+++ b/test/mitmproxy/data/addonscripts/error.py
@@ -1,8 +1,8 @@
from mitmproxy import ctx
-def running():
- ctx.log.info("error running")
+def load(loader):
+ ctx.log.info("error load")
def request(flow):
| Addons: `running` is invoked twice.
##### Steps to reproduce the problem:
1. Write an addon that implements `running()`
2. Running is invoked twice on startup.
Addons: `running` is invoked twice.
##### Steps to reproduce the problem:
1. Write an addon that implements `running()`
2. Running is invoked twice on startup.
| +1
👍
+1
+1
👍
+1 | 2021-11-27T13:07:08 |
mitmproxy/mitmproxy | 5,020 | mitmproxy__mitmproxy-5020 | [
"5017"
] | 3fbf3cf8eeccf3338c0ce3fe0d4c4ab7df91cdc5 | 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
@@ -389,7 +389,6 @@ def send_response(self, already_streamed: bool = False):
if self.flow.response.trailers:
yield SendHttp(ResponseTrailers(self.stream_id, self.flow.response.trailers), self.context.client)
- yield SendHttp(ResponseEndOfMessage(self.stream_id), self.context.client)
if self.flow.response.status_code == 101:
if is_websocket:
@@ -405,7 +404,10 @@ def send_response(self, already_streamed: bool = False):
yield commands.Log(f"{self.debug}[http] upgrading to {self.child_layer}", "debug")
yield from self.child_layer.handle_event(events.Start())
self._handle_event = self.passthrough
- return
+
+ # delay sending EOM until the child layer is set up,
+ # we may get data immediately and need to be prepared to handle it.
+ yield SendHttp(ResponseEndOfMessage(self.stream_id), self.context.client)
def check_body_size(self, request: bool) -> layer.CommandGenerator[bool]:
"""
| diff --git a/test/mitmproxy/proxy/layers/test_websocket.py b/test/mitmproxy/proxy/layers/test_websocket.py
--- a/test/mitmproxy/proxy/layers/test_websocket.py
+++ b/test/mitmproxy/proxy/layers/test_websocket.py
@@ -109,6 +109,61 @@ def test_upgrade(tctx):
assert flow().websocket.messages[1].type == Opcode.BINARY
+def test_upgrade_streamed(tctx):
+ """If the HTTP response is streamed, we may get early data from the client."""
+ tctx.server.address = ("example.com", 80)
+ tctx.server.state = ConnectionState.OPEN
+ flow = Placeholder(HTTPFlow)
+
+ def enable_streaming(flow: HTTPFlow):
+ flow.response.stream = True
+
+ assert (
+ Playbook(http.HttpLayer(tctx, HTTPMode.transparent))
+ >> DataReceived(tctx.client,
+ b"GET / HTTP/1.1\r\n"
+ b"Connection: upgrade\r\n"
+ b"Upgrade: websocket\r\n"
+ b"Sec-WebSocket-Version: 13\r\n"
+ b"\r\n")
+ << http.HttpRequestHeadersHook(flow)
+ >> reply()
+ << http.HttpRequestHook(flow)
+ >> reply()
+ << SendData(tctx.server, b"GET / HTTP/1.1\r\n"
+ b"Connection: upgrade\r\n"
+ b"Upgrade: websocket\r\n"
+ b"Sec-WebSocket-Version: 13\r\n"
+ b"\r\n")
+ >> DataReceived(tctx.server, b"HTTP/1.1 101 Switching Protocols\r\n"
+ b"Upgrade: websocket\r\n"
+ b"Connection: Upgrade\r\n"
+ b"\r\n")
+ << http.HttpResponseHeadersHook(flow)
+ >> reply(side_effect=enable_streaming)
+ << SendData(tctx.client, b"HTTP/1.1 101 Switching Protocols\r\n"
+ b"Upgrade: websocket\r\n"
+ b"Connection: Upgrade\r\n"
+ b"\r\n")
+ << http.HttpResponseHook(flow)
+ >> DataReceived(tctx.client, masked_bytes(b"\x81\x0bhello world")) # early !!
+ >> reply(to=-2)
+ << websocket.WebsocketStartHook(flow)
+ >> reply()
+ << websocket.WebsocketMessageHook(flow)
+ >> reply()
+ << SendData(tctx.server, masked(b"\x81\x0bhello world"))
+ >> DataReceived(tctx.server, b"\x82\nhello back")
+ << websocket.WebsocketMessageHook(flow)
+ >> reply()
+ << SendData(tctx.client, b"\x82\nhello back")
+ >> DataReceived(tctx.client, masked_bytes(b"\x81\x0bhello again"))
+ << websocket.WebsocketMessageHook(flow)
+ >> reply()
+ << SendData(tctx.server, masked(b"\x81\x0bhello again"))
+ )
+
+
@pytest.fixture()
def ws_testdata(tctx):
tctx.server.address = ("example.com", 80)
| "AssertionError: Unexpected event type at HttpStream.state_done" in presence of transformation function
#### Problem Description
```
127.0.0.1:50894: GET https://alive.github.com/_sockets/u/<redacted>/ws?session=<redacted>
<< 101 Switching Protocols (content missing)
127.0.0.1:50894: mitmproxy has crashed!
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 279, in server_event
for command in layer_commands:
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 255, in handle_event
yield from self._handle(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 699, in _handle_event
yield from self.event_to_child(stream, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 617, in passthrough
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 85, in _handle_event
yield from self.event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/tls.py", line 320, in event_to_child
yield from super().event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 104, in event_to_child
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 85, in _handle_event
yield from self.event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 104, in event_to_child
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 699, in _handle_event
yield from self.event_to_child(stream, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 764, in event_to_child
yield from self.event_to_child(conn, command.event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 761, in event_to_child
yield from self.event_to_child(stream, command.event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 136, in _handle_event
yield from self.client_state(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/utils.py", line 23, in _check_event_type
raise AssertionError(
AssertionError: Unexpected event type at HttpStream.state_done: Expected no events, got RequestData(stream_id=1, data=bytearray(b'<redacted>')).
127.0.0.1:50874: mitmproxy has crashed!
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 279, in server_event
for command in layer_commands:
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 255, in handle_event
yield from self._handle(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 740, in _handle_event
yield from self.event_to_child(handler, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 617, in passthrough
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 72, in _handle_event
yield from self.receive_data(event.data)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/tls.py", line 261, in receive_data
yield from self.event_to_child(
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/tls.py", line 320, in event_to_child
yield from super().event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 104, in event_to_child
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 85, in _handle_event
yield from self.event_to_child(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/tunnel.py", line 104, in event_to_child
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 740, in _handle_event
yield from self.event_to_child(handler, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 761, in event_to_child
yield from self.event_to_child(stream, command.event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 138, in _handle_event
yield from self.server_state(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/utils.py", line 23, in _check_event_type
raise AssertionError(
AssertionError: Unexpected event type at HttpStream.state_done: Expected no events, got ResponseEndOfMessage(stream_id=1).
```
Similar exceptions also pop up for, among other things, [https://push.services.mozilla.com/]() and [https://qa.sockets.stackexchange.com/]().
#### Steps to reproduce the behavior:
1.
```python
from time import sleep
class Test:
def _process_chunk(self, data):
sleep(0.01) # not reproducible without this
return data # noop
def responseheaders(self, flow):
flow.response.stream = self._process_chunk
addons = [
Test(),
]
```
2. Visit GitHub, StackExchange, or wait for Firefox to phone home.
#### System Information
```
Mitmproxy: 7.0.4
Python: 3.9.1
OpenSSL: OpenSSL 1.1.1g 21 Apr 2020
Platform: Linux-5.10.13-gentoo-x86_64-AMD_Ryzen_5_PRO_4650G_with_Radeon_Graphics-with-glibc2.32
```
| Reproducible locally:
```sh
while :; do date; sleep .5; done | websocat -b ws-l:0.0.0.0:12345 stdio:
```
(Not reproducible without binary server messages, hence `-b`)
```html
<link rel="icon" type="image/gif" href="data:image/gif;base64,R0lGODlhAQABAPAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="> <!-- don't spam logs with missing favicons -->
<script>
let s = new WebSocket('ws://192.168.1.2:12345/ws');
s.onopen = function(e) {
console.log('opened');
s.send('asdf');
};
s.onmessage = function(ev) {
console.log('rcvd', ev.data);
};
s.onclose = function(event) {
console.log('closed');
};
s.onerror = function(err) {
console.log('error', err.message);
};
</script>
```
(Not reproducible without initial `send()`)
JS console:
```
opened
closed
```
(note lack of rcvd messages)
```
127.0.0.1:38420: server connect 192.168.1.2:12345
127.0.0.1:38420: Streaming response from 192.168.1.2.
127.0.0.1:38420: GET http://192.168.1.2:12345/ws
Host: 192.168.1.2:12345
<...snip...>
Upgrade: websocket
<< 101 Switching Protocols (content missing)
Sec-WebSocket-Accept: 5jIIDxDZEKGf9M1XZ1XIHtUDZzY=
Connection: Upgrade
Upgrade: websocket
127.0.0.1:38420: mitmproxy has crashed!
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 279, in server_event
for command in layer_commands:
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 255, in handle_event
yield from self._handle(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 699, in _handle_event
yield from self.event_to_child(stream, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 617, in passthrough
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 699, in _handle_event
yield from self.event_to_child(stream, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 764, in event_to_child
yield from self.event_to_child(conn, command.event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 761, in event_to_child
yield from self.event_to_child(stream, command.event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 136, in _handle_event
yield from self.client_state(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/utils.py", line 23, in _check_event_type
raise AssertionError(
AssertionError: Unexpected event type at HttpStream.state_done: Expected no events, got RequestData(stream_id=1, data=bytearray(b'\x81\x84r\xb8\xbfG\x13\xcb\xdb!')).
127.0.0.1:38420: mitmproxy has crashed!
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/server.py", line 279, in server_event
for command in layer_commands:
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 255, in handle_event
yield from self._handle(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 740, in _handle_event
yield from self.event_to_child(handler, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 617, in passthrough
for command in self.child_layer.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 740, in _handle_event
yield from self.event_to_child(handler, event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 761, in event_to_child
yield from self.event_to_child(stream, command.event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 749, in event_to_child
for command in child.handle_event(event):
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layer.py", line 144, in handle_event
command = command_generator.send(send)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/layers/http/__init__.py", line 138, in _handle_event
yield from self.server_state(event)
File "/usr/lib/python3.9/site-packages/mitmproxy/proxy/utils.py", line 23, in _check_event_type
raise AssertionError(
AssertionError: Unexpected event type at HttpStream.state_done: Expected no events, got ResponseData(stream_id=1, data=b'\x82 Mon Dec 27 06:28:29 PM MSK 2021\n').
```
It's worth noting that I also see random connection hangs and glitches that don't seem to be related to websockets at all, but those are way harder to reproduce. | 2021-12-27T15:53:30 |
mitmproxy/mitmproxy | 5,040 | mitmproxy__mitmproxy-5040 | [
"5034"
] | ef8c88da1f1e7bc15989e285b5565f9540c6d5f1 | diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -223,11 +223,14 @@ async def handle_connection(self, connection: Connection) -> None:
except asyncio.CancelledError as e:
cancelled = e
break
- else:
- self.server_event(events.DataReceived(connection, data))
- for transport in self.transports.values():
- if transport.writer is not None:
- await transport.writer.drain()
+
+ self.server_event(events.DataReceived(connection, data))
+
+ try:
+ await self.drain_writers()
+ except asyncio.CancelledError as e:
+ cancelled = e
+ break
if cancelled is None:
connection.state &= ~ConnectionState.CAN_READ
@@ -253,6 +256,19 @@ async def handle_connection(self, connection: Connection) -> None:
if cancelled:
raise cancelled
+ async def drain_writers(self):
+ """
+ Drain all writers to create some backpressure. We won't continue reading until there's space available in our
+ write buffers, so if we cannot write fast enough our own read buffers run full and the TCP recv stream is throttled.
+ """
+ for transport in self.transports.values():
+ if transport.writer is not None:
+ try:
+ await transport.writer.drain()
+ except OSError as e:
+ if transport.handler is not None:
+ asyncio_utils.cancel_task(transport.handler, f"Error sending data: {e}")
+
async def on_timeout(self) -> None:
self.log(f"Closing connection due to inactivity: {self.client}")
handler = self.transports[self.client].handler
| Client sometimes using dead connection
#### Problem Description
I have noticed that web browsers sometimes stall loading images or pages. I get it both on an iPad with Safari and a Fedora with Firefox. It especially happens with pass-through connections but also without.
I think I have tracked down the bug to _mitmproxy/proxy/server.py_ where in ConnectionHandler.handle_connection() there is the following loop:
```
while True:
try:
data = await reader.read(65535)
if not data:
raise OSError("Connection closed by peer.")
except OSError:
break
except asyncio.CancelledError as e:
cancelled = e
break
else:
self.server_event(events.DataReceived(connection, data))
for transport in self.transports.values():
if transport.writer is not None:
await transport.writer.drain()
```
The final drain() can actually throw and if it does all the connection management following the loop is not properly done, leaving the connection in a strange state. My suggested fix that made it work without further hick-ups for me is this:
```
reader = self.transports[connection].reader
writer = self.transports[connection].writer
assert reader
assert writer
while True:
...
else:
self.server_event(events.DataReceived(connection, data))
for transport in self.transports.values():
if transport.writer is not None:
try:
await transport.writer.drain()
except OSError as e:
if transport.writer == writer:
cancelled = e
break
else:
continue
break
```
#### Steps to reproduce the behavior:
1. Start mitmdump as transparent proxy with '--ignore-hosts .com'
2. Go to apple.com
3. Quickly click on links, attempt to abort a page load with a re-load of the same page
#### System Information
Mitmproxy: 8.0.0.dev (+200, commit ef8c88d)
Python: 3.9.7
OpenSSL: OpenSSL 1.1.1m 14 Dec 2021
Platform: Linux-4.18.0-348.2.1.el8_5.x86_64-x86_64-with-glibc2.28
| Honestly I was dreading to even open this issue after reading "Client sometimes ..." in the title, but turns out there is a positive surprise in here. 😁 This is super super interesting, thank you very much! 🍰
1. I can't trigger `.drain()` to raise on my system, but that might be OS-specific. Out of interest, would you mind posting the full OSError `repr()` here?
2. How did you approach finding this? Any tips/tricks you can share?
3. It may be useful to just cancel any handler (not just the current one) if we cannot write. Could you verify that the following patch also works for you?
```diff
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -227,7 +227,11 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
self.server_event(events.DataReceived(connection, data))
for transport in self.transports.values():
if transport.writer is not None:
- await transport.writer.drain()
+ try:
+ await transport.writer.drain()
+ except OSError as e:
+ if transport.handler is not None:
+ asyncio_utils.cancel_task(transport.handler, f"cannot drain writer: {e}")
```
Thanks for looking into this! Apart from this issue the new sansio design rocks! I can even scroll around in Google Maps and the CPU usage of the proxy machine remains in the one digit range. With V4 this was laggy with >100% load. Cool.
> 1. I can't trigger `.drain()` to raise on my system, but that might be OS-specific. Out of interest, would you mind posting the full OSError `repr()` here?
When I log a `repr(e)` when drain() raises an exception then the log entry reads:
```ConnectionResetError('Connection lost')```
Out of curiosity I also added an `except asyncio.CancelledError as e:` after `drain()` and that also sometimes catches an exception (meaning my fix wasn't complete...):
```CancelledError('client disconnected')```
I wonder what it takes to reproduce this on your side. I run mitmdump in transparent mode (easy for me to add and remove my machines), from the git repo directly on a CentOS 8 Stream on a laptop. Basically it provides a gateway from my WIFI network to the ADSL router.
> 2. How did you approach finding this? Any tips/tricks you can share?
The hard way, with tcpdump/wireshark, `--set proxy_debug=true` and putting `self.log()` all over the place in _server.py_. With tcpdump I noticed that when a page load stalled that I could still tap on links and that the browser then still sent data to the proxy after that transport has been closed (HTTP/2 does that) so it had to be the stream management at a low level. I also noticed that for the connection that stalled, the log entry `client disconnect` in `ConnectionHandler()` after `watch.cancel()` was missing for that connection. After narrowing down this far I started inserting `self.log()` until I found that the one after `drain()` sometimes was not logging.
What also helped me on the way was to add this to my script:
```
def error(flow: http.HTTPFlow):
if flow.error is not None:
ctx.log("FLOWERROR " + str(flow.error))
```
> 3. It may be useful to just cancel any handler (not just the current one) if we cannot write. Could you verify that the following patch also works for you?
>
>
> ```diff
> --- a/mitmproxy/proxy/server.py
> +++ b/mitmproxy/proxy/server.py
> @@ -227,7 +227,11 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
> self.server_event(events.DataReceived(connection, data))
> for transport in self.transports.values():
> if transport.writer is not None:
> - await transport.writer.drain()
> + try:
> + await transport.writer.drain()
> + except OSError as e:
> + if transport.handler is not None:
> + asyncio_utils.cancel_task(transport.handler, f"cannot drain writer: {e}")
> ```
I just tried this variant a bit. It made it worse for pass-through connections (apple.com on my iPad). After the first or second click already the connection stalls consistently. I guess the approach is too aggressive.
For normal HTTP/2 connections it worked OK but I did get a _502 Bad Gateway_ when reading heise.de after a few pages. The `error()` in my script logged:
```
FLOWERROR HTTP/2 protocol error: Invalid input ConnectionInputs.RECV_HEADERS in state ConnectionState.CLOSED
```
I do not fully understand the code in _server.py_, for instance, why there is a need to drain all writers, not just the one from this connection. I am not strongly advocating my solution, so far it is just the most solid for me, even if I apparently missed the `CancelError`s. If you have more suggestions then I will try them out, this is dead easy for me to reproduce. Which still worries me, apparenly nobody else had this issue so far... :)
> Thanks for looking into this! Apart from this issue the new sansio design rocks! I can even scroll around in Google Maps and the CPU usage of the proxy machine remains in the one digit range. With V4 this was laggy with >100% load. Cool.
Excellent. Very happy to hear that. 😃
> I wonder what it takes to reproduce this on your side. I run mitmdump in transparent mode (easy for me to add and remove my machines), from the git repo directly on a CentOS 8 Stream on a laptop.
That's helpful, thanks. My main driver is a Windows machine in regular mode, so that's quite a different stack.
> The hard way, with tcpdump/wireshark, `--set proxy_debug=true` and putting `self.log()` all over the place in _server.py_. With tcpdump I noticed that when a page load stalled that I could still tap on links and that the browser then still sent data to the proxy after that transport has been closed (HTTP/2 does that) so it had to be the stream management at a low level. I also noticed that for the connection that stalled, the log entry `client disconnect` in `ConnectionHandler()` after `watch.cancel()` was missing for that connection. After narrowing down this far I started inserting `self.log()` until I found that the one after `drain()` sometimes was not logging.
Very impressive! I'm actually somewhat puzzled which part silently swallows the OSError here, I definitely need to figure out why exceptions are ignored and correct that. But let's focus on the initial issue here.
> I just tried this variant a bit. It made it worse for pass-through connections (apple.com on my iPad). After the first or second click already the connection stalls consistently. I guess the approach is too aggressive.
This confused me for a bit, but I think I have a working theory now: When a coroutine/task is cancelled, it continues to run normally until the next `await` statement, which throws a `CancelledError`. What's may be happening here is that we first cancel our very own connection handler task we're currently in, and after that then `drain()` another transport. As we have already cancelled our own coroutine this `await drain()` immediately throws a `CancelledError`, which as you correctly pointed out both of us did not catch before! The problem just happens to be much more visible in my patch.
> I do not fully understand the code in server.py, for instance, why there is a need to drain all writers
We do that to create backpressure. Assume you have a very fast connection to your laptop, a slower connection upstream, and you want to upload a large file. mitmproxy would very quickly read everything from your local device and then have an immense send buffer for the upstream connection. So while mitmproxy is slowly shoveling bits upstream, your client is done uploading for minutes already, hits a timeout, and aborts the connection[^1].
Draining the upstream connection aftere each read means we wait for space in the upstream send buffer to be available before we continue reading from the downstream socket again. In other words, while we drain the upstream send buffer, our own downstream receive buffer fills up and the OS' TCP implementation signals to downstream that they need to slow down. Does that make sense?
> If you have more suggestions then I will try them out, this is dead easy for me to reproduce. Which still worries me, apparenly nobody else had this issue so far... :)
Here's a revised patch that does catch the CancelledError. Could you test that and see how it works?
```diff
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -223,11 +223,21 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
except asyncio.CancelledError as e:
cancelled = e
break
- else:
- self.server_event(events.DataReceived(connection, data))
- for transport in self.transports.values():
- if transport.writer is not None:
+
+ self.server_event(events.DataReceived(connection, data))
+
+ # Drain all writers to create some backpressure. We won't continue reading until there's space available in
+ # our write buffers, so our own read buffers run full and the TCP recv stream is throttled.
+ for transport in self.transports.values():
+ if transport.writer is not None:
+ try:
await transport.writer.drain()
+ except OSError as e:
+ if transport.handler is not None:
+ asyncio_utils.cancel_task(transport.handler, f"Error sending data: {e}")
+ except asyncio.CancelledError as e:
+ cancelled = e
+ break
```
[^1]: I'm assuming a streamed request body (or plain TCP) here. If mitmproxy is told not to stream this issue still exists.
I'll reply in full and run extensive tests in the evening. One question though on the new patch that you may be able to answer before that:
> Here's a revised patch that does catch the CancelledError. Could you test that and see how it works?
>
> ```diff
> --- a/mitmproxy/proxy/server.py
> +++ b/mitmproxy/proxy/server.py
> @@ -223,11 +223,21 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
> except asyncio.CancelledError as e:
> cancelled = e
> break
> - else:
> - self.server_event(events.DataReceived(connection, data))
> - for transport in self.transports.values():
> - if transport.writer is not None:
> +
> + self.server_event(events.DataReceived(connection, data))
> +
> + # Drain all writers to create some backpressure. We won't continue reading until there's space available in
> + # our write buffers, so our own read buffers run full and the TCP recv stream is throttled.
> + for transport in self.transports.values():
> + if transport.writer is not None:
> + try:
> await transport.writer.drain()
> + except OSError as e:
> + if transport.handler is not None:
> + asyncio_utils.cancel_task(transport.handler, f"Error sending data: {e}")
> + except asyncio.CancelledError as e:
> + cancelled = e
> + break
> ```
That last break, it will only exit the inner loop which does not make sense to me. I would either ignore the exception and continue draining the rest of the writers as well or exit the outer loop with an 'else - continue - break' construct similar to what I used in my patch. Since you set cancelled I guess you want the later.
Yes, good catch. Let's break out entirely. :)
Here's a revised revised patch that should break out:
```diff
diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py
index 4b26b23c6..7af7f09d6 100644
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -223,11 +223,14 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
except asyncio.CancelledError as e:
cancelled = e
break
- else:
- self.server_event(events.DataReceived(connection, data))
- for transport in self.transports.values():
- if transport.writer is not None:
- await transport.writer.drain()
+
+ self.server_event(events.DataReceived(connection, data))
+
+ try:
+ await self.drain_writers()
+ except asyncio.CancelledError as e:
+ cancelled = e
+ break
if cancelled is None:
connection.state &= ~ConnectionState.CAN_READ
@@ -253,6 +256,19 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
if cancelled:
raise cancelled
+ async def drain_writers(self):
+ """
+ Drain all writers to create some backpressure. We won't continue reading until there's space available in our
+ write buffers, so if we cannot write fast enough our own read buffers run full and the TCP recv stream is throttled.
+ """
+ for transport in self.transports.values():
+ if transport.writer is not None:
+ try:
+ await transport.writer.drain()
+ except OSError as e:
+ if transport.handler is not None:
+ asyncio_utils.cancel_task(transport.handler, f"Error sending data: {e}")
+
async def on_timeout(self) -> None:
self.log(f"Closing connection due to inactivity: {self.client}")
handler = self.transports[self.client].handler
```
> Here's a revised revised patch that should break out:
>
> ```diff
> diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py
> index 4b26b23c6..7af7f09d6 100644
> --- a/mitmproxy/proxy/server.py
> +++ b/mitmproxy/proxy/server.py
> @@ -223,11 +223,14 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
> except asyncio.CancelledError as e:
> cancelled = e
> break
> - else:
> - self.server_event(events.DataReceived(connection, data))
> - for transport in self.transports.values():
> - if transport.writer is not None:
> - await transport.writer.drain()
> +
> + self.server_event(events.DataReceived(connection, data))
> +
> + try:
> + await self.drain_writers()
> + except asyncio.CancelledError as e:
> + cancelled = e
> + break
>
> if cancelled is None:
> connection.state &= ~ConnectionState.CAN_READ
> @@ -253,6 +256,19 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
> if cancelled:
> raise cancelled
>
> + async def drain_writers(self):
> + """
> + Drain all writers to create some backpressure. We won't continue reading until there's space available in our
> + write buffers, so if we cannot write fast enough our own read buffers run full and the TCP recv stream is throttled.
> + """
> + for transport in self.transports.values():
> + if transport.writer is not None:
> + try:
> + await transport.writer.drain()
> + except OSError as e:
> + if transport.handler is not None:
> + asyncio_utils.cancel_task(transport.handler, f"Error sending data: {e}")
> +
> async def on_timeout(self) -> None:
> self.log(f"Closing connection due to inactivity: {self.client}")
> handler = self.transports[self.client].handler
> ```
I have applied this patch and tried various websites, Youtube, Google Maps, etc. and there was not a single delayed load or missing image during my hours of surfing. In the logs I did not see any suspicious server-side errors. So I think the above fix works great.
Thanks for the solution! I keep the patch in my checkout until it is also committed to the main branch. But this issue can be closed I think. | 2022-01-07T22:05:52 |
|
mitmproxy/mitmproxy | 5,078 | mitmproxy__mitmproxy-5078 | [
"5054"
] | d47fd3e9c32d4ceac4274cb5b807879a5d9af48e | diff --git a/mitmproxy/http.py b/mitmproxy/http.py
--- a/mitmproxy/http.py
+++ b/mitmproxy/http.py
@@ -1185,7 +1185,10 @@ def refresh(self, now=None):
d = parsedate_tz(self.headers[i])
if d:
new = mktime_tz(d) + delta
- self.headers[i] = formatdate(new, usegmt=True)
+ try:
+ self.headers[i] = formatdate(new, usegmt=True)
+ except OSError: # pragma: no cover
+ pass # value out of bounds on Windows only (which is why we exclude it from coverage).
c = []
for set_cookie_header in self.headers.get_all("set-cookie"):
try:
| diff --git a/test/mitmproxy/test_http.py b/test/mitmproxy/test_http.py
--- a/test/mitmproxy/test_http.py
+++ b/test/mitmproxy/test_http.py
@@ -613,6 +613,11 @@ def test_refresh(self):
m.side_effect = ValueError
r.refresh(n)
+ # Test negative unixtime, which raises on at least Windows.
+ r.headers["date"] = pre = "Mon, 01 Jan 1601 00:00:00 GMT"
+ r.refresh(946681202)
+ assert r.headers["date"] == pre
+
class TestHTTPFlow:
| response.refresh() gives OSError on Windows
```
Navigating to secondary url:https://www.bing.com/search?q=barack+obama+quotes
Navigating to url https://www.bing.com/search?q=barack+obama+quotes iteration 25
Addon error: Traceback (most recent call last):'
Error: b' File "C:\\Users\\task_1641995085\\build\\venv\\lib\\site-packages\\mozproxy\\backends\\mitm\\scripts\\alt-serverplayback.py", line 250, in request'
Error: b' response.refresh()'
Error: b' File "mitmproxy\\http.py", line 1188, in refresh'
Error: b' File "email\\utils.py", line 147, in formatdate'
Error: b'OSError: [Errno 22] Invalid argument'
```
This error only occurs on windows. I have been able to run mitmproxy from source with our test harness, and added log statements to output the parameters being passed to `formatdate`. I've verified in a python terminal that the parameters are valid.
This did not occur until we updated from mitmproxy 5.1.1 to 7.0.4. I've checked the source code for the previous versions, and though the code has been moved around, there is no difference in the calls being made in `response.refresh()`
| Thanks for the clear report! Could you share the concrete arguments passed to `formatdate` please?
Well we know `usegmt` is always true, but when looking for examples of `new`, I've found the issue. Most of the time it prints valid values like `1641850717.0697627`, but the next value that was printed out was negative: `-11644030337.930237`, which returns the above `OSError` when run in a python prompt.
could it be caused by this line? `delta = now - self.timestamp_start`
Unsure how else we'd end up with a negative value, or why this only occurs on Windows
Hm - this definitely is weird. Could you potentially add a
```python
print(f"{delta=} {self.timestamp_start=} {i=} {self.headers[i]=} {d=} {new=}")
```
log statement and report back what that yields for the offending flow?
`delta=1133852.30330801 self.timestamp_start=1641407457.1147604 i='last-modified' self.headers[i]='Mon, 01 Jan 1601 00:00:00 GMT' d=(1601, 1, 1, 0, 0, 0, 0, 1, -1, 0) new=-11643339747.696692`
`delta=1133830.6156322956 self.timestamp_start=1641407480.3896403 i='last-modified' self.headers[i]='Mon, 01 Jan 1601 00:00:00 GMT' d=(1601, 1, 1, 0, 0, 0, 0, 1, -1, 0) new=-11643339769.384367`
two examples of flows with negative values
every negative value has the same `last-modified` date of Jan 1, 1601 | 2022-01-18T21:52:18 |
mitmproxy/mitmproxy | 5,080 | mitmproxy__mitmproxy-5080 | [
"5077"
] | 53f60c88b1d7e4d817194f186d9730b32953d1a7 | 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
@@ -244,7 +244,9 @@ def state_stream_request_body(self, event: Union[RequestData, RequestEndOfMessag
elif isinstance(event, RequestEndOfMessage):
if callable(self.flow.request.stream):
chunks = self.flow.request.stream(b"")
- if isinstance(chunks, bytes):
+ if chunks == b"":
+ chunks = []
+ elif isinstance(chunks, bytes):
chunks = [chunks]
for chunk in chunks:
yield SendHttp(RequestData(self.stream_id, chunk), self.context.server)
@@ -336,7 +338,9 @@ def state_stream_response_body(self, event: events.Event) -> layer.CommandGenera
elif isinstance(event, ResponseEndOfMessage):
if callable(self.flow.response.stream):
chunks = self.flow.response.stream(b"")
- if isinstance(chunks, bytes):
+ if chunks == b"":
+ chunks = []
+ elif isinstance(chunks, bytes):
chunks = [chunks]
for chunk in chunks:
yield SendHttp(ResponseData(self.stream_id, chunk), self.context.client)
| Small bug in handling of streamed data from callable flow.*.stream
I have finished writing an addon to save streamed requests and responses to files. While getting it to work I stumbled over the problem that some sites fail to load with:
```
HTTP/2 connection closed: <ConnectionTerminated error_code:ErrorCodes.FRAME_SIZE_ERROR, last_stream_id:1, additional_data:None>
```
The issue is that the callable `flow.request.stream` and `flow.response.stream` at the end of the stream is supposed to return the zero byte string it receives which is then sent as an HTTP/2 chunk. For responses this may be tolerated by the client but for requests it breaks protocol.
I fixed this issue with this patch which I _think_ is probably the best way to fix it given the contract with the callable:
```diff
diff --git a/mitmproxy/proxy/layers/http/__init__.py b/mitmproxy/proxy/layers/http/__init__.py
index 0b134f7bb..9068e9020 100644
--- a/mitmproxy/proxy/layers/http/__init__.py
+++ b/mitmproxy/proxy/layers/http/__init__.py
@@ -244,10 +244,14 @@ class HttpStream(layer.Layer):
elif isinstance(event, RequestEndOfMessage):
if callable(self.flow.request.stream):
chunks = self.flow.request.stream(b"")
+ send = True
if isinstance(chunks, bytes):
+ if len(chunks) == 0:
+ send = False
chunks = [chunks]
- for chunk in chunks:
- yield SendHttp(RequestData(self.stream_id, chunk), self.context.server)
+ if send:
+ for chunk in chunks:
+ yield SendHttp(RequestData(self.stream_id, chunk), self.context.server)
self.flow.request.timestamp_end = time.time()
yield HttpRequestHook(self.flow)
@@ -336,10 +340,14 @@ class HttpStream(layer.Layer):
elif isinstance(event, ResponseEndOfMessage):
if callable(self.flow.response.stream):
chunks = self.flow.response.stream(b"")
+ send = True
if isinstance(chunks, bytes):
+ if len(chunks) == 0:
+ send = False
chunks = [chunks]
- for chunk in chunks:
- yield SendHttp(ResponseData(self.stream_id, chunk), self.context.client)
+ if send:
+ for chunk in chunks:
+ yield SendHttp(ResponseData(self.stream_id, chunk), self.context.client)
yield from self.send_response(already_streamed=True)
@expect(ResponseData, ResponseTrailers, ResponseEndOfMessage)
```
| 2022-01-19T20:35:50 |
||
mitmproxy/mitmproxy | 5,110 | mitmproxy__mitmproxy-5110 | [
"5108"
] | 59033371e82fdfbce46281db9c16132a7f867ca8 | diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -176,14 +176,7 @@ async def open_connection(self, command: commands.OpenConnection) -> None:
else:
addr = human.format_address(command.connection.address)
self.log(f"server connect {addr}")
- connected_hook = asyncio_utils.create_task(
- self.handle_hook(server_hooks.ServerConnectedHook(hook_data)),
- name=f"handle_hook(server_connected) {addr}",
- client=self.client.peername,
- )
- if not connected_hook:
- return # this should not be needed, see asyncio_utils.create_task
-
+ await self.handle_hook(server_hooks.ServerConnectedHook(hook_data))
self.server_event(events.OpenConnectionCompleted(command, None))
# during connection opening, this function is the designated handler that can be cancelled.
@@ -201,7 +194,6 @@ async def open_connection(self, command: commands.OpenConnection) -> None:
self.log(f"server disconnect {addr}")
command.connection.timestamp_end = time.time()
- await connected_hook # wait here for this so that closed always comes after connected.
await self.handle_hook(server_hooks.ServerDisconnectedHook(hook_data))
async def handle_connection(self, connection: Connection) -> None:
diff --git a/mitmproxy/proxy/server_hooks.py b/mitmproxy/proxy/server_hooks.py
--- a/mitmproxy/proxy/server_hooks.py
+++ b/mitmproxy/proxy/server_hooks.py
@@ -20,7 +20,6 @@ class ClientDisconnectedHook(commands.StartHook):
"""
A client connection has been closed (either by us or the client).
"""
- blocking = False
client: connection.Client
@@ -50,7 +49,6 @@ class ServerConnectedHook(commands.StartHook):
"""
Mitmproxy has connected to a server.
"""
- blocking = False
data: ServerConnectionHookData
@@ -59,5 +57,4 @@ class ServerDisconnectedHook(commands.StartHook):
"""
A server connection has been closed (either by us or the server).
"""
- blocking = False
data: ServerConnectionHookData
| Wait for connection hooks to finish before calling HTTP hooks
#### Problem Description
This issue is in response to your comment https://github.com/mitmproxy/mitmproxy/issues/4207#issuecomment-907014592
> Ah, you are hitting a special case here: We are not waiting for server_connected to complete before notifying the HTTP layer that the connection has been established (I didn't think this would be useful to anyone and it surely isn't faster). If you have a concrete use case here please open a separate issue, this should be straightforward to adjust. In fact at the moment it's a bit more complicated because we don't block.
To summarize: I'm doing rather heavy work in every hook and communicate with a different service (gRPC calls to Node.js that process the hooks). When using `@concurrent` (and probably same with async hooks) hooks such as `server_connected` and `request` are racing each other (I think that's actually the only case). With synchronous hooks this cannot happen because whatever I do in `server_connected` blocks the entire proxy.
```py
import time
from mitmproxy.script import concurrent
@concurrent
def client_connected(data):
print('>>> client_connected')
time.sleep(2)
print('<<< client_connected')
@concurrent
def server_connect(data):
print('>>> server_connect')
time.sleep(2)
print('<<< server_connect')
@concurrent
def server_connected(data):
print('>>> server_connected')
time.sleep(2)
print('<<< server_connected')
@concurrent
def request(flow):
print('>>> request')
time.sleep(2)
print('<<< request')
@concurrent
def response(flow):
print('>>> response')
time.sleep(2)
print('<<< response')
@concurrent
def client_disconnected(data):
print('>>> client_disconnected')
time.sleep(2)
print('<<< client_disconnected')
@concurrent
def server_disconnected(data):
print('>>> server_disconnected')
time.sleep(2)
print('<<< server_disconnected')
```
As you can see `server_connected` and `request` are interleaved.
```
>>> client_connected
<<< client_connected
>>> server_connect
<<< server_connect
>>> server_connected
>>> request
<<< server_connected
<<< request
>>> response
<<< response
>>> client_disconnected
<<< client_disconnected
>>> server_disconnected
<<< server_disconnected
```
#### Proposal
Wait for the connection hooks to finish before continuing with the HTTP layer.
#### Alternatives
I could leave the connection event synchronous so that the always block and finish. But depending on the number of clients and servers this would mostly diminish the effect of making all other hooks async or concurrent.
| If you remove the `blocking: bool = False` lines in https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/proxy/server_hooks.py and then change
https://github.com/mitmproxy/mitmproxy/blob/83b43b93a7ac6cf2bfe557964fd63b376e158e25/mitmproxy/proxy/server.py#L179-L185
to
```python
await self.handle_hook(server_hooks.ServerConnectedHook(hook_data))
```
and remove
https://github.com/mitmproxy/mitmproxy/blob/83b43b93a7ac6cf2bfe557964fd63b376e158e25/mitmproxy/proxy/server.py#L204
you should be done. I don't have the time to test that properly, but if it works for you please go ahead and open a PR. :)
Thanks, that looks easy enough. I'll look into it! | 2022-02-04T13:20:41 |
|
mitmproxy/mitmproxy | 5,186 | mitmproxy__mitmproxy-5186 | [
"4746",
"4746"
] | 6f0587734e2525eab49ba9a1d2052c87922125c7 | diff --git a/mitmproxy/addons/proxyserver.py b/mitmproxy/addons/proxyserver.py
--- a/mitmproxy/addons/proxyserver.py
+++ b/mitmproxy/addons/proxyserver.py
@@ -90,6 +90,14 @@ def load(self, loader):
"proxy_debug", bool, False,
"Enable debug logs in the proxy core.",
)
+ loader.add_option(
+ "normalize_outbound_headers", bool, True,
+ """
+ Normalize outgoing HTTP/2 header names, but emit a warning when doing so.
+ HTTP/2 does not allow uppercase header names. This option makes sure that HTTP/2 headers set
+ in custom scripts are lowercased before they are sent.
+ """,
+ )
def running(self):
self.master = ctx.master
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
@@ -269,6 +269,13 @@ def normalize_h1_headers(headers: List[Tuple[bytes, bytes]], is_client: bool) ->
return headers
+def normalize_h2_headers(headers: List[Tuple[bytes, bytes]]) -> CommandGenerator[None]:
+ for i in range(len(headers)):
+ if not headers[i][0].islower():
+ yield Log(f"Lowercased {repr(headers[i][0]).lstrip('b')} header as uppercase is not allowed with HTTP/2.")
+ headers[i] = (headers[i][0].lower(), headers[i][1])
+
+
class Http2Server(Http2Connection):
h2_conf = h2.config.H2Configuration(
**Http2Connection.h2_conf_defaults,
@@ -290,7 +297,10 @@ def _handle_event(self, event: Event) -> CommandGenerator[None]:
(b":status", b"%d" % event.response.status_code),
*event.response.headers.fields
]
- if not event.response.is_http2:
+ if event.response.is_http2:
+ if self.context.options.normalize_outbound_headers:
+ yield from normalize_h2_headers(headers)
+ else:
headers = normalize_h1_headers(headers, False)
self.h2_conn.send_headers(
@@ -407,6 +417,8 @@ def _handle_event2(self, event: Event) -> CommandGenerator[None]:
if event.request.is_http2:
hdrs = list(event.request.headers.fields)
+ if self.context.options.normalize_outbound_headers:
+ yield from normalize_h2_headers(hdrs)
else:
headers = event.request.headers
if not event.request.authority and "host" in headers:
| diff --git a/test/mitmproxy/proxy/layers/http/test_http2.py b/test/mitmproxy/proxy/layers/http/test_http2.py
--- a/test/mitmproxy/proxy/layers/http/test_http2.py
+++ b/test/mitmproxy/proxy/layers/http/test_http2.py
@@ -10,7 +10,7 @@
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes
-from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
+from mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import http
@@ -353,19 +353,19 @@ def enable_response_streaming(flow: HTTPFlow):
@pytest.mark.xfail(reason="inbound validation turned on to protect against request smuggling")
-def test_no_normalization(tctx):
[email protected]("normalize", [True, False])
+def test_no_normalization(tctx, normalize):
"""Test that we don't normalize headers when we just pass them through."""
+ tctx.options.normalize_outbound_headers = normalize
server = Placeholder(Server)
flow = Placeholder(HTTPFlow)
playbook, cff = start_h2_client(tctx)
- request_headers = example_request_headers + (
- (b"Should-Not-Be-Capitalized! ", b" :) "),
- )
- response_headers = example_response_headers + (
- (b"Same", b"Here"),
- )
+ request_headers = list(example_request_headers) + [(b"Should-Not-Be-Capitalized! ", b" :) ")]
+ request_headers_lower = [(k.lower(), v) for (k, v) in request_headers]
+ response_headers = list(example_response_headers) + [(b"Same", b"Here")]
+ response_headers_lower = [(k.lower(), v) for (k, v) in response_headers]
initial = Placeholder(bytes)
assert (
@@ -385,18 +385,22 @@ def test_no_normalization(tctx):
hyperframe.frame.SettingsFrame,
hyperframe.frame.HeadersFrame,
]
- assert hpack.hpack.Decoder().decode(frames[1].data, True) == list(request_headers)
+ assert hpack.hpack.Decoder().decode(frames[1].data, True) == request_headers_lower if normalize else request_headers
sff = FrameFactory()
- assert (
+ (
playbook
>> DataReceived(server, sff.build_headers_frame(response_headers, flags=["END_STREAM"]).serialize())
<< http.HttpResponseHeadersHook(flow)
>> reply()
<< http.HttpResponseHook(flow)
>> reply()
- << SendData(tctx.client, cff.build_headers_frame(response_headers, flags=["END_STREAM"]).serialize())
)
+ if normalize:
+ playbook << Log("Lowercased 'Same' header as uppercase is not allowed with HTTP/2.")
+ hdrs = response_headers_lower if normalize else response_headers
+ assert playbook << SendData(tctx.client, cff.build_headers_frame(hdrs, flags=["END_STREAM"]).serialize())
+
assert flow().request.headers.fields == ((b"Should-Not-Be-Capitalized! ", b" :) "),)
assert flow().response.headers.fields == ((b"Same", b"Here"),)
| Warn when sending uppercase HTTP/2 headers
The following addon will make some requests fail with HTTP/2 protocol errors:
```python
def request(flow):
flow.request.headers["Content-Type"] = "application/json"
```
It's not immediately obvious what's the problem here, but HTTP/2 headers may only be lowercase. We are smart enough to automatically fix that for requests that we received as HTTP/1, but otherwise we intentionally just keep things as-is. This is hard to debug for addon authors, we should emit a warning if we see uppercase HTTP/2 headers being sent.
Warn when sending uppercase HTTP/2 headers
The following addon will make some requests fail with HTTP/2 protocol errors:
```python
def request(flow):
flow.request.headers["Content-Type"] = "application/json"
```
It's not immediately obvious what's the problem here, but HTTP/2 headers may only be lowercase. We are smart enough to automatically fix that for requests that we received as HTTP/1, but otherwise we intentionally just keep things as-is. This is hard to debug for addon authors, we should emit a warning if we see uppercase HTTP/2 headers being sent.
| Why do we *intentionally just keep things as-is*?
Why not apply the same smartness by default, and maybe provide a `--strict` mode or similar? Less surprises for most users, and for the advanced users, they can opt into a strict mode for tinkering with the protocols.
Fair point. Let's add an option and normalize by default.
Why do we *intentionally just keep things as-is*?
Why not apply the same smartness by default, and maybe provide a `--strict` mode or similar? Less surprises for most users, and for the advanced users, they can opt into a strict mode for tinkering with the protocols.
Fair point. Let's add an option and normalize by default. | 2022-03-16T09:43:41 |
mitmproxy/mitmproxy | 5,224 | mitmproxy__mitmproxy-5224 | [
"5109"
] | a63c96ce72850a987f8345d2b6a9b40ff820d85d | diff --git a/mitmproxy/addons/tlsconfig.py b/mitmproxy/addons/tlsconfig.py
--- a/mitmproxy/addons/tlsconfig.py
+++ b/mitmproxy/addons/tlsconfig.py
@@ -118,7 +118,9 @@ def tls_start_client(self, tls_start: tls.TlsData) -> None:
if tls_start.ssl_conn is not None:
return # a user addon has already provided the pyOpenSSL context.
- client: connection.Client = tls_start.context.client
+ assert isinstance(tls_start.conn, connection.Client)
+
+ client: connection.Client = tls_start.conn
server: connection.Server = tls_start.context.server
entry = self.get_cert(tls_start.context)
@@ -168,8 +170,11 @@ def tls_start_server(self, tls_start: tls.TlsData) -> None:
if tls_start.ssl_conn is not None:
return # a user addon has already provided the pyOpenSSL context.
+ assert isinstance(tls_start.conn, connection.Server)
+
client: connection.Client = tls_start.context.client
- server: connection.Server = tls_start.context.server
+ # tls_start.conn may be different from tls_start.context.server, e.g. an upstream HTTPS proxy.
+ server: connection.Server = tls_start.conn
assert server.address
if ctx.options.ssl_insecure:
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
@@ -351,7 +351,8 @@ def start_handshake(self) -> layer.CommandGenerator[None]:
self.tunnel_state = tunnel.TunnelState.CLOSED
else:
yield from self.start_tls()
- yield from self.receive_handshake_data(b"")
+ if self.tls:
+ yield from self.receive_handshake_data(b"")
def event_to_child(self, event: events.Event) -> layer.CommandGenerator[None]:
if self.wait_for_clienthello:
| diff --git a/test/mitmproxy/proxy/layers/test_modes.py b/test/mitmproxy/proxy/layers/test_modes.py
--- a/test/mitmproxy/proxy/layers/test_modes.py
+++ b/test/mitmproxy/proxy/layers/test_modes.py
@@ -70,6 +70,7 @@ def test_upstream_https(tctx):
<< SendData(upstream, clienthello)
)
assert upstream().address == ("example.mitmproxy.org", 8081)
+ assert upstream().sni == "example.mitmproxy.org"
assert (
proxy2
>> DataReceived(tctx2.client, clienthello())
diff --git a/test/mitmproxy/proxy/tutils.py b/test/mitmproxy/proxy/tutils.py
--- a/test/mitmproxy/proxy/tutils.py
+++ b/test/mitmproxy/proxy/tutils.py
@@ -201,9 +201,13 @@ def __bool__(self):
x.connection.timestamp_end = 1624544787
self.actual.append(x)
+ cmds: typing.List[commands.Command] = []
try:
- cmds: typing.List[commands.Command] = list(self.layer.handle_event(x))
+ # consume them one by one so that we can extend the log with all commands until traceback.
+ for cmd in self.layer.handle_event(x):
+ cmds.append(cmd)
except Exception:
+ self.actual.extend(cmds)
self.actual.append(_TracebackInPlaybook(traceback.format_exc()))
break
| Wrong SNI hostname used for upstream HTTPS proxy
#### Problem Description
When using mitmproxy with an upstream HTTPS proxy, it will attempt to use the client connection's target host for SNI in the outer TLS connection, and will subsequently fail to validate that connection and return "502 Bad Gateway" -- "Certificate verify failed: Hostname mismatch"
#### Steps to reproduce the behavior:
1. Start mitmproxy with an HTTPS upstream proxy, e.g. `mitmproxy --mode upstream:https://example.com:1234 --upstream-auth user:pass`
2. Issue an HTTP request, e.g. `curl -ski -x http://127.0.0.1:8080 https://api.ipify.org`
3. mitmproxy will log `warn: 127.0.0.1:55584: Server TLS handshake failed. Certificate verify failed: Hostname mismatch` and return a `502 Bad Gateway` error with reason `Certificate verify failed: Hostname mismatch` to the client.
4. A packet capture of the upstream traffic shows that mitmproxy tried to use `api.ipify.org` for SNI in the TLS connection to the upstream proxy.
#### System Information
```
Mitmproxy: 7.0.4
Python: 3.8.10
OpenSSL: OpenSSL 1.1.1l 24 Aug 2021
Platform: Linux-5.4.0-26-generic-x86_64-with-glibc2.29
```
| I haven't verified the issue yet, but thank you already for the clear report! | 2022-03-29T08:21:57 |
mitmproxy/mitmproxy | 5,228 | mitmproxy__mitmproxy-5228 | [
"3427"
] | 66dd1585609febfaadf1f0c31fe1ae8b113985b3 | diff --git a/mitmproxy/tools/console/flowlist.py b/mitmproxy/tools/console/flowlist.py
--- a/mitmproxy/tools/console/flowlist.py
+++ b/mitmproxy/tools/console/flowlist.py
@@ -1,8 +1,11 @@
+import typing
+from functools import lru_cache
+
import urwid
+import mitmproxy.tools.console.master
from mitmproxy.tools.console import common
from mitmproxy.tools.console import layoutwidget
-import mitmproxy.tools.console.master
class FlowItem(urwid.WidgetWrap):
@@ -40,6 +43,7 @@ def keypress(self, size, key):
class FlowListWalker(urwid.ListWalker):
+ master: "mitmproxy.tools.console.master.ConsoleMaster"
def __init__(self, master):
self.master = master
@@ -47,13 +51,14 @@ def __init__(self, master):
def positions(self, reverse=False):
# The stub implementation of positions can go once this issue is resolved:
# https://github.com/urwid/urwid/issues/294
- ret = range(self.master.commands.execute("view.properties.length"))
+ ret = range(self.master.view.get_length())
if reverse:
return reversed(ret)
return ret
def view_changed(self):
self._modified()
+ self._get.cache_clear()
def get_focus(self):
if not self.master.view.focus.flow:
@@ -65,19 +70,17 @@ def set_focus(self, index):
if self.master.commands.execute("view.properties.inbounds %d" % index):
self.master.view.focus.index = index
- def get_next(self, pos):
- pos = pos + 1
- if not self.master.commands.execute("view.properties.inbounds %d" % pos):
+ @lru_cache(maxsize=None)
+ def _get(self, pos: int) -> typing.Tuple[typing.Optional[FlowItem], typing.Optional[int]]:
+ if not self.master.view.inbounds(pos):
return None, None
- f = FlowItem(self.master, self.master.view[pos])
- return f, pos
+ return FlowItem(self.master, self.master.view[pos]), pos
+
+ def get_next(self, pos):
+ return self._get(pos + 1)
def get_prev(self, pos):
- pos = pos - 1
- if not self.master.commands.execute("view.properties.inbounds %d" % pos):
- return None, None
- f = FlowItem(self.master, self.master.view[pos])
- return f, pos
+ return self._get(pos - 1)
class FlowListBox(urwid.ListBox, layoutwidget.LayoutWidget):
| Improve flow list performance
mitmproxy's flow list is very slow: holding the down arrow to move the cursor causes it to visibly lag on my machine. The lag affects not just the UI, but the entire application - requests are slowed down as well.
Profiling (using `cProfile`) identified the bottlenecks as:
- For every redraw, `FlowListWalker` was creating several instances of `FlowList` *per flow* for every redraw. This is because `urwid.ListBox` needs to iterate over the list more than once per redraw.
- `FlowListWalker` uses `commands.execute` instead of calling `View` methods directly. The formatting and parsing of commands adds an additional performance cost. (This is a recent performance regression only in git, introduced by @madt1m in commit 773c9535146991af38f954cb4d3b0ead9d7485c5.)
- `raw_format_flow` incorrectly had the entire `Flow` object added to its argument list. This caused needless work for `@lru_cache`, as it was hashing the entire `Flow` object as part of the cache key, and probably causing unnecessary cache misses as `Flow` properties changed without affecting the displayed content. (This is a performance regression, introduced by @Kriechi in commit d86cb76e5ba38c51b7d6017fb151e4946e3fb916.)
Profiling result:

The changes in this pull request rectify these problems, thus improving performance somewhat.
| Thanks for tracking this down! This looks like amazing work!
I do not recall the reasoning for changing `raw_format_flow` - so your guess is as good as mine.
If you could make our linting system happy as well, I think we can merge:
`mitmproxy/tools/console/flowlist.py:38: error: Need type annotation for '__cache'`
Ehi there! Nice piece of work you did here. Actually, there's a reason behind that change: the general assumption at the time of commit was that directly accessing the View addon from other tools is somewhat hacky, and this eventually lead to a Codebase clean-up, to make tools and add-ons communicate between themselves only through our command layer.
> This looks like amazing work!
Thanks!
> I do not recall the reasoning for changing `raw_format_flow` - so your guess is as good as mine.
From the commit in question (d86cb76e5ba38c51b7d6017fb151e4946e3fb916), it looks like at the time it wasn't obvious that all information about the flow was intended to be passed through the tuple parameter, so that `@lru_cache` would use it as a cache key.
> the general assumption at the time of commit was that directly accessing the View addon from other tools is somewhat hacky, and this eventually lead to a Codebase clean-up, to make tools and add-ons communicate between themselves only through our command layer.
Yes, that makes sense; unfortunately, this particular change turned out to be on a hot path, so directly accessing internals may be worthwhile.
> Looking a bit further down the profile graph, it seems like we could significantly alleviate this by lru-caching `command.verify_arg_signature` (14.61%) and `command.lexer` (5.3%)? That would also benefit other parts of mitmproxy.
Those sound like good directions for research. I'll need to figure out how to reliably profile this code path, so that I can get quantitative measurements of any improvements.
> How about we just use `functools.lru_cache(maxsize=None)` for `__get` and then call `self.__get.cache_clear()` in `view_changed`?
Sounds good, I'll do this for now.
> I'll need to figure out how to reliably profile this code path, so that I can get quantitative measurements of any improvements.
I wrote the following mitmproxy script:
```python
from mitmproxy import ctx
import timeit
NUM_FLOWS = 100
NUM_SAMPLES = 10
NUM_ITERS = 1
def do_nav():
for i in range(NUM_FLOWS):
ctx.master.commands.call("console.nav.down")
for i in range(NUM_FLOWS):
ctx.master.commands.call("console.nav.up")
def do_bench(func):
smallest_time = float('inf')
for n in range(NUM_SAMPLES):
time = timeit.timeit(func, number=NUM_ITERS)
if smallest_time > time:
smallest_time = time
return smallest_time
ctx.log.alert('Measuring overhead...')
overhead = do_bench(do_nav)
for i in range(NUM_FLOWS):
ctx.master.commands.call("view.flows.create", "get", "https://example.com/" + str(i))
ctx.log.alert('Benchmarking...')
time_all = do_bench(do_nav)
time = time_all - overhead
class ResultPrinter:
def done(self):
print('Result: ' + str(time) + ' (overhead ' + str(overhead) + ')')
addons = [
ResultPrinter()
]
ctx.master.commands.call("console.exit")
```
With the above, I now have a clearer picture of which changes are actually worthwhile.
The first commit does not register a measurable performance improvement (I'm guessing I made a mistake when assessing the change), so we can probably drop it. The third commit also does not register an improvement in this benchmark, however the benchmark does not attempt to simulate false cache misses due to things changing in the flow that would not be reflected in `raw_format_flow`'s first argument. Not sure how often those might occur in practice, but I would argue in its favour at least for pedantic correctness' sake.
The second commit, however, does result in a very significant speedup, going from 3.09 to 1.66 seconds according to the above script.
> Looking a bit further down the profile graph, it seems like we could significantly alleviate this by lru-caching `command.verify_arg_signature` (14.61%) and `command.lexer` (5.3%)? That would also benefit other parts of mitmproxy.
It doesn't look like these changes would be as trivial. `command.verify_arg_signature` has a `list` in its argument list, which is apparently not compatible with `@lru_cache`. `command.lexer` merely returns a lexer, so some refactoring would be required to memoise it.
> It doesn't look like these changes would be as trivial. `command.verify_arg_signature` has a `list` in its argument list, which is apparently not compatible with `@lru_cache`. `command.lexer` merely returns a lexer, so some refactoring would be required to memoise it.
`command.lexer`: Yeah, I misread the callgraph. It shouldn't be too difficult though - we'd need to move this chunk into its own function and cache it, which doesn't seem to have external dependencies. https://github.com/mitmproxy/mitmproxy/blob/e2bcca47b1ad8040451cbd95039acf200e9b0e84/mitmproxy/command.py#L160-L176
---------------
For `command.verify_arg_signature`, we can replace
https://github.com/mitmproxy/mitmproxy/blob/e2bcca47b1ad8040451cbd95039acf200e9b0e84/mitmproxy/command.py#L87
with
```
verify_arg_signature(self.func, tuple(args), None)
```
and
https://github.com/mitmproxy/mitmproxy/blob/e2bcca47b1ad8040451cbd95039acf200e9b0e84/mitmproxy/command.py#L274
with
```
verify_arg_signature(function, args, kwargs or None)
```
Could you give this a spin on your machine to have a consistent test setup? Thanks so much! 😃 😊
OK, I'm testing this patch:
```diff
diff --git a/mitmproxy/command.py b/mitmproxy/command.py
index 27f0921d..5283f328 100644
--- a/mitmproxy/command.py
+++ b/mitmproxy/command.py
@@ -14,10 +14,11 @@ from mitmproxy import exceptions
import mitmproxy.types
-def verify_arg_signature(f: typing.Callable, args: list, kwargs: dict) -> None:
[email protected]_cache(maxsize=200)
+def verify_arg_signature(f: typing.Callable, args: tuple, kwargs: tuple) -> None:
sig = inspect.signature(f)
try:
- sig.bind(*args, **kwargs)
+ sig.bind(*list(args), **dict(kwargs))
except TypeError as v:
raise exceptions.CommandError("command argument mismatch: %s" % v.args[0])
@@ -31,6 +32,28 @@ def lexer(s):
return lex
[email protected]_cache(maxsize=200)
+def lex_string(cmdstr):
+ buf = io.StringIO(cmdstr)
+ parts: typing.List[str] = []
+ lex = lexer(buf)
+ while 1:
+ remainder = cmdstr[buf.tell():]
+ try:
+ t = lex.get_token()
+ except ValueError:
+ parts.append(remainder)
+ break
+ if not t:
+ break
+ parts.append(t)
+ if not parts:
+ parts = [""]
+ elif cmdstr.endswith(" "):
+ parts.append("")
+ return parts
+
+
def typename(t: type) -> str:
"""
Translates a type to an explanatory string.
@@ -84,7 +107,7 @@ class Command:
return "%s %s%s" % (self.path, params, ret)
def prepare_args(self, args: typing.Sequence[str]) -> typing.List[typing.Any]:
- verify_arg_signature(self.func, list(args), {})
+ verify_arg_signature(self.func, tuple(args), ())
remainder: typing.Sequence[str] = []
if self.has_positional:
@@ -157,23 +180,7 @@ class CommandManager(mitmproxy.types._CommandBase):
"""
Parse a possibly partial command. Return a sequence of ParseResults and a sequence of remainder type help items.
"""
- buf = io.StringIO(cmdstr)
- parts: typing.List[str] = []
- lex = lexer(buf)
- while 1:
- remainder = cmdstr[buf.tell():]
- try:
- t = lex.get_token()
- except ValueError:
- parts.append(remainder)
- break
- if not t:
- break
- parts.append(t)
- if not parts:
- parts = [""]
- elif cmdstr.endswith(" "):
- parts.append("")
+ parts = lex_string(cmdstr)
parse: typing.List[ParseResult] = []
params: typing.List[type] = []
@@ -271,7 +278,7 @@ def command(path):
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
- verify_arg_signature(function, args, kwargs)
+ verify_arg_signature(function, args, tuple(kwargs.items()))
return function(*args, **kwargs)
wrapper.__dict__["command_path"] = path
return wrapper
```
Applied to master, it brings the benchmark result from 2.98 to 1.96, which is quite significant! By itself, it's not as great as the second commit in this PR, though. If the patch looks good, I can add it to this PR too.
Awesome, thanks! 🍰
The diff you posted is uncontroversial I think and I'd be more than happy to merge it right away. Would you mind opening a separate PR for that?
Your second commit breaks some isolations we wanted to establish so it might be a bit controversial. I have no particular opinion on that tradeoff, but @cortesi might. @cortesi, any thoughts?
I cherry-picked your third commit onto master. :-)
> Would you mind opening a separate PR for that?
OK, here it is: https://github.com/mitmproxy/mitmproxy/pull/3428
> Your second commit breaks some isolations we wanted to establish so it might be a bit controversial.
Perhaps an additional, abstract interface of sending commands using a more performance-friendly model (tuples and identifiers instead of strings)? | 2022-03-29T17:18:16 |
|
mitmproxy/mitmproxy | 5,230 | mitmproxy__mitmproxy-5230 | [
"3969",
"3965"
] | 31add1a7c001f940e960479ffab229f4e53487a8 | diff --git a/mitmproxy/addons/cut.py b/mitmproxy/addons/cut.py
--- a/mitmproxy/addons/cut.py
+++ b/mitmproxy/addons/cut.py
@@ -8,7 +8,6 @@
from mitmproxy import flow
from mitmproxy import ctx
from mitmproxy import certs
-from mitmproxy.utils import strutils
import mitmproxy.types
import pyperclip
@@ -54,6 +53,14 @@ def extract(cut: str, f: flow.Flow) -> typing.Union[str, bytes]:
return str(current or "")
+def extract_str(cut: str, f: flow.Flow) -> str:
+ ret = extract(cut, f)
+ if isinstance(ret, bytes):
+ return repr(ret)
+ else:
+ return ret
+
+
class Cut:
@command.command("cut")
def cut(
@@ -110,10 +117,8 @@ def save(
with open(path, "a" if append else "w", newline='', encoding="utf8") as tfp:
writer = csv.writer(tfp)
for f in flows:
- vals = [extract(c, f) for c in cuts]
- writer.writerow(
- [strutils.always_str(x) or "" for x in vals] # type: ignore
- )
+ vals = [extract_str(c, f) for c in cuts]
+ writer.writerow(vals)
ctx.log.alert("Saved %s cuts over %d flows as CSV." % (len(cuts), len(flows)))
except OSError as e:
ctx.log.error(str(e))
@@ -132,16 +137,14 @@ def clip(
v: typing.Union[str, bytes]
fp = io.StringIO(newline="")
if len(cuts) == 1 and len(flows) == 1:
- v = extract(cuts[0], flows[0])
- fp.write(strutils.always_str(v)) # type: ignore
+ v = extract_str(cuts[0], flows[0])
+ fp.write(v)
ctx.log.alert("Clipped single cut.")
else:
writer = csv.writer(fp)
for f in flows:
- vals = [extract(c, f) for c in cuts]
- writer.writerow(
- [strutils.always_str(v) for v in vals]
- )
+ vals = [extract_str(c, f) for c in cuts]
+ writer.writerow(vals)
ctx.log.alert("Clipped %s cuts as CSV." % len(cuts))
try:
pyperclip.copy(fp.getvalue())
| 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
@@ -59,6 +59,12 @@ def test_extract(tdata):
assert "CERTIFICATE" in cut.extract("server_conn.certificate_list", tf)
+def test_extract_str():
+ tf = tflow.tflow()
+ tf.request.raw_content = b"\xFF"
+ assert cut.extract_str("request.raw_content", tf) == r"b'\xff'"
+
+
def test_headername():
with pytest.raises(exceptions.CommandError):
cut.headername("header[foo.")
@@ -115,7 +121,7 @@ def test_cut_save(tmpdir):
tctx.command(c.save, "@all", "request.method", f)
assert qr(f).splitlines() == [b"GET", b"GET"]
tctx.command(c.save, "@all", "request.method,request.content", f)
- assert qr(f).splitlines() == [b"GET,content", b"GET,content"]
+ assert qr(f).splitlines() == [b"GET,b'content'", b"GET,b'content'"]
@pytest.mark.parametrize("exception, log_message", [
| fix crash at cut addon
fixes #3965
App crashed when trying to copy the response content using "cut.clip @focus response.raw_content"
Crash log:
```
Traceback (most recent call last):
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/master.py", line 86, in run_loop
loop()
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/main_loop.py", line 286, in run
self._run()
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/main_loop.py", line 384, in _run
self.event_loop.run()
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/main_loop.py", line 1484, in run
reraise(*exc_info)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/compat.py", line 58, in reraise
raise value
File "/usr/local/Cellar/[email protected]/3.8.1/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/events.py", line 81, in _run
self._context.run(self._callback, *self._args)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/raw_display.py", line 403, in <lambda>
wrapper = lambda: self.parse_input(
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/raw_display.py", line 502, in parse_input
callback(processed, processed_codes)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/main_loop.py", line 411, in _update
self.process_input(keys)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/main_loop.py", line 511, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/tools/console/window.py", line 310, in keypress
k = super().keypress(size, k)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/urwid/container.py", line 1119, in keypress
return self.footer.keypress((maxcol,),key)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/tools/console/statusbar.py", line 201, in keypress
return self.ab.keypress(*args, **kwargs)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/tools/console/statusbar.py", line 149, in keypress
self.prompt_execute(text)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/tools/console/statusbar.py", line 169, in prompt_execute
msg = p(txt)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/tools/console/statusbar.py", line 115, in execute_command
execute(txt)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/tools/console/commandexecutor.py", line 17, in __call__
ret = self.master.commands.execute(cmd)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/command.py", line 265, in execute
return self._call_strings(command_name, args)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/command.py", line 251, in _call_strings
return self.commands[command_name].call(args)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/command.py", line 122, in call
ret = self.func(*bound_args.args, **bound_args.kwargs)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/command.py", line 295, in wrapper
return function(*args, **kwargs)
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/addons/cut.py", line 133, in clip
fp.write(strutils.always_str(v)) # type: ignore
File "/usr/local/Cellar/mitmproxy/5.0.1_1/libexec/lib/python3.8/site-packages/mitmproxy/utils/strutils.py", line 26, in always_str
return str_or_bytes.decode(*decode_args)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
```
| @mhils we can use this or with codecs, we can use try and catch with different encoding but I think this approach is better. what are your thoughts about this?
Any hint about the build-wheel error?
Shouldn't we just switch to `io.BinaryIO` in the case where exactly one column and row is selected?
https://github.com/mitmproxy/mitmproxy/blob/dac0bfe786a8d1dfdd97f29d6bb262ed258153fa/mitmproxy/addons/cut.py#L130-L134
> If there is exactly one row and one column, the data is written to file as-is, with raw bytes preserved.
The user is trying to copy bytes to the clipboard, no need to force it into a string. Or is there? I don't know if you can even put raw bytes to the clipboard?
---
**Welp** https://github.com/asweigart/pyperclip/issues/63 :smile:
Is this even a good idea? What's the use case? Maybe we should just tell the user that they cannot put binary data into the clipboard and that they can export it to a file instead?
>The user is trying to copy bytes to the clipboard, no need to force it into a string. Or is there? I don't know if you can even put raw bytes to the clipboard?
>
I think pyperclip does not support binary data for the clipboard.
>Is this even a good idea? What's the use case? Maybe we should just tell the user that they cannot put binary data into the clipboard and that they can export it to a file instead?
>
May be we can notify that if one row and one column and binary data then it's decoded, right now it shows
`# Send cuts to the clipboard. If there are multiple flows or cuts, the`
`# format is UTF-8 encoded CSV. If there is exactly one row and one`
`# column, the data is written to file as-is, with raw bytes preserved.`
`cut.clip flows cuts`
I don't think it's right for single cut?
But let's hear maintainers thought about this.
I wasn't even aware of the `cut.clip` feature so I'm not sure what the original intended use-cases are. I thought about this and if I would use it to quickly process the data somewhere else (e.g. paste it into CyberChef). I would like binary stuff to be Base64 encoded. I think that's the most common way to represent binary as strings and well supported. I can't think of a use-case where you would actually want raw bytes in your clipboard, I personally don't know where I could actually paste it. I mean maybe I could paste an image right into Gimp?
So maybe we can unify this and also include Base64 in the CSV (if it cannot be represented as text)?
But like I said I didn't even know about this feature and I'm not invested in it at all. I'm just trying to kill some time rn :smile:
> Just guessing the encoding is can of works we really don't want to open.
I mean :see_no_evil:
https://github.com/mitmproxy/mitmproxy/blob/7fdcbb09e6034ab1f76724965cfdf45f3d775129/mitmproxy/net/http/message.py#L172-L187
This is not about guessing encoding for arbitrary binary data. The original error report / crash was about `raw_content` which can be gzip or whatever. And mitmproxy also crashes when `content` is an image or other binary. So this definitely needs to be fixed. The question is how much responsibility do we give the user? If they're using `content` instead of `text` they might already made a decision that they want binary? So the only question is how we represent these binary cases, without doing any magic. In the best case we could add them raw to the clipboard, which pyperclip doesn't support. And also I haven't checked what happens with binary if it's a CSV, maybe the csv lib already does something useful we can steal?
>And also I haven't checked what happens with binary if it's a CSV
>
This also does not store bytes directly that's why when writing to file in more row or column the data is converted into str.
As saving to file also failed(in case of either more flow or more cuts) along with copy to clipboard as we try to decode them. if we try to preserve the raw data how about we store data as python byte object in the string(example "b'\x80\x40something'") in both cases.
@mhils, @Prinzhorn
It's definitely a bug that we crash here, but for most purposes, you really want to use `.text` instead of `.raw_content` with `cut.clip`. Binary content and the clipboard doesn't mix well.
Thanks, @mhils for the help. cheers | 2022-03-30T12:18:52 |
mitmproxy/mitmproxy | 5,322 | mitmproxy__mitmproxy-5322 | [
"5297"
] | c91685efeb995659a5dd8dfdbbb65be5c55f2ac0 | 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
@@ -1,5 +1,4 @@
import asyncio
-import mailcap
import mimetypes
import os
import os.path
@@ -154,28 +153,20 @@ def spawn_external_viewer(self, data, contenttype):
# read-only to remind the user that this is a view function
os.chmod(name, stat.S_IREAD)
- cmd = None
- shell = False
+ # hm which one should get priority?
+ c = (
+ os.environ.get("MITMPROXY_EDITOR")
+ or os.environ.get("PAGER")
+ or os.environ.get("EDITOR")
+ )
+ if not c:
+ c = "less"
+ cmd = shlex.split(c)
+ cmd.append(name)
- if contenttype:
- c = mailcap.getcaps()
- cmd, _ = mailcap.findmatch(c, contenttype, filename=name)
- if cmd:
- shell = True
- if not cmd:
- # hm which one should get priority?
- c = (
- os.environ.get("MITMPROXY_EDITOR")
- or os.environ.get("PAGER")
- or os.environ.get("EDITOR")
- )
- if not c:
- c = "less"
- cmd = shlex.split(c)
- cmd.append(name)
with self.uistopped():
try:
- subprocess.call(cmd, shell=shell)
+ subprocess.call(cmd, shell=False)
except:
signals.status_message.send(
message="Can't start external viewer: %s" % " ".join(c)
| mailcap deprecated for Python 3.11 removed for Python 3.13
I've been following this Python dev mailing thread which proposed to deprecate `mailcap` from the standard library: https://mail.python.org/archives/list/[email protected]/thread/EB2BS4DBWSTBIOPQL5QTBSIOBORWSCMJ/
After a code search I noticed that you were the only library I recognized which used this module:
https://grep.app/search?q=import%20mailcap
https://github.com/mitmproxy/mitmproxy/blob/4f7f64c516341c586c9f8cb6593217ff3e359351/mitmproxy/tools/console/master.py#L2
Please be aware the Steering Council just accepted this deprecation proposal meaning the module will be deprecated for Python 3.11 removed for Python 3.13.
(I don't have any affiliation with this decision, I am just trying to proactively raise awareness)
| Thanks for the heads-up! 😃
I think this is a very reasonable deprecation and deprecation schedule, we can easily work around this on our end. :)
@mhils Are you aware of any library that could substitute `mailcap`, what's your idea here? I poked around this, and it seems that it is used in only one place for opening a request/response in default application (if content type is correctly recognized), but it works only on Unix-compatible OSes as `mailcap` uses `*/etc/*` files for detection:
https://github.com/python/cpython/blob/f6656163de483003697d510031827b7512056d55/Lib/mailcap.py#L51-L65
So on macOS (which I use) and Windows mitmproxy falls back to `less` or other editor:
https://github.com/mitmproxy/mitmproxy/blob/9d1821e920d6225578a0b65881d203a537186298/mitmproxy/tools/console/master.py#L160-L175
The easiest solution would be to just have `less` or other pager open a file, but I'm not sure if you want to kind of degrade the feature on Unix OSes.
@KORraNpl: I had not heard about/used mailcap before this issue was opened, so I naturally have no idea. I traced it back to https://github.com/mitmproxy/mitmproxy/commit/cb0e3287090786fad566feb67ac07b8ef361b2c3 though (Feb 2010), so that was quite fun. 😄
Honestly I feel like there isn't much harm done if we just remove that part.
There's of course opportunity to improve things, maybe `xdg-open` on Linux or `os.startfile(..., "edit")` on Windows? We do need to think critically about whether we want to essentially enable code execution here, so maybe just removing it is good enough. | 2022-05-05T20:18:58 |
|
mitmproxy/mitmproxy | 5,324 | mitmproxy__mitmproxy-5324 | [
"5319",
"5319"
] | a201adebe174897c1c10e8d78028d44ea0b6fc92 | diff --git a/mitmproxy/contentviews/__init__.py b/mitmproxy/contentviews/__init__.py
--- a/mitmproxy/contentviews/__init__.py
+++ b/mitmproxy/contentviews/__init__.py
@@ -47,6 +47,8 @@
on_add = blinker.Signal()
"""A new contentview has been added."""
+on_remove = blinker.Signal()
+"""A contentview has been removed."""
def get(name: str) -> Optional[View]:
@@ -68,6 +70,7 @@ def add(view: View) -> None:
def remove(view: View) -> None:
views.remove(view)
+ on_remove.send(view)
def safe_to_print(lines, encoding="utf8"):
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
@@ -50,7 +50,8 @@ def __init__(self, master):
super().__init__([])
self.show()
self.last_displayed_body = None
- contentviews.on_add.connect(self.contentview_added)
+ contentviews.on_add.connect(self.contentview_changed)
+ contentviews.on_remove.connect(self.contentview_changed)
@property
def view(self):
@@ -60,11 +61,12 @@ def view(self):
def flow(self) -> mitmproxy.flow.Flow:
return self.master.view.focus.flow
- def contentview_added(self, view):
+ def contentview_changed(self, view):
# this is called when a contentview addon is live-reloaded.
# we clear our cache and then rerender
self._get_content_view.cache_clear()
- self.show()
+ if self.master.window.current_window("flowview"):
+ self.show()
def focus_changed(self):
f = self.flow
| diff --git a/test/mitmproxy/tools/console/conftest.py b/test/mitmproxy/tools/console/conftest.py
--- a/test/mitmproxy/tools/console/conftest.py
+++ b/test/mitmproxy/tools/console/conftest.py
@@ -42,5 +42,6 @@ async def console(monkeypatch) -> ConsoleTestMaster: # noqa
opts = options.Options()
m = ConsoleTestMaster(opts)
opts.server = False
+ opts.console_mouse = False
await m.running()
return m
diff --git a/test/mitmproxy/tools/console/test_contentview.py b/test/mitmproxy/tools/console/test_contentview.py
new file mode 100644
--- /dev/null
+++ b/test/mitmproxy/tools/console/test_contentview.py
@@ -0,0 +1,39 @@
+from mitmproxy.test import tflow
+from mitmproxy import contentviews
+from mitmproxy.contentviews.base import format_text
+
+
+class TContentView(contentviews.View):
+ name = "Test View"
+
+ def __call__(self, data, **metadata):
+ return "TContentView", format_text("test_content")
+
+ def render_priority(self, data, *, content_type=None, **metadata) -> float:
+ return 2
+
+
+async def test_contentview_flowview(console):
+ assert "Flows" in console.screen_contents()
+ flow = tflow.tflow()
+ flow.request.headers["content-type"] = "text/html"
+ await console.load_flow(flow)
+ assert ">>" in console.screen_contents()
+ console.type("<enter>")
+ assert "Flow Details" in console.screen_contents()
+ assert "XML" in console.screen_contents()
+
+ view = TContentView()
+ contentviews.add(view)
+ assert "XML" not in console.screen_contents()
+ assert "TContentView" in console.screen_contents()
+ contentviews.remove(view)
+ assert "XML" in console.screen_contents()
+ assert "TContentView" not in console.screen_contents()
+
+ console.type("q")
+ assert "Flows" in console.screen_contents()
+ contentviews.add(view)
+ console.type("<enter>")
+ assert "Flow Details" in console.screen_contents()
+ assert "TContentView" in console.screen_contents()
| Reloading a script with a custom view fails with "CommandError: Not viewing a flow."
#### Problem Description
Hot-reloading a script with a custom View doesn't work after any flow has been viewed. The reload crashes with an exception and the view is not loaded.
#### Steps to reproduce the behavior:
1. Create a script `test.py` with the following contents:
```python
from mitmproxy import contentviews, ctx, flow, http
from mitmproxy.contentviews.base import format_text
import typing
class TestView(contentviews.View):
name = "Test"
def __call__(self, data, **metadata):
return "Test HTML", format_text(data)
def render_priority(self, data: bytes, *, content_type: typing.Optional[str] = None, **metadata) -> float:
return float(data.startswith(b'<!')) * 2
def load(self, l):
contentviews.add(self)
def done(self):
contentviews.remove(self)
addons = [
TestView(),
]
```
2. Launch `mitmproxy` as `mitmproxy -s test.py`
3. Browse to `example.com` (e.g. `http_proxy=localhost:8080 curl example.com`).
4. A request should appear in mitmproxy. Open the request view, then return back to the main request list.
5. Make any edit to the `test.py` file and save.
6. An error appears in the error log:
```
error: Addon error: Traceback (most recent call last):
File "test.py", line 16, in load
contentviews.add(self)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/contentviews/__init__.py", line 52, in add
on_add.send(view)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/blinker/base.py", line 266, in send
return [(receiver, receiver(sender, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/blinker/base.py", line 266, in <listcomp>
return [(receiver, receiver(sender, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/flowview.py", line 66, in contentview_added
self.show()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/tabs.py", line 73, in show
body = self.tabs[self.tab_offset % len(self.tabs)][1](),
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/flowview.py", line 122, in view_request
return self.conn_text(flow.request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/flowview.py", line 326, in conn_text
viewmode = self.master.commands.call("console.flowview.mode")
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/command.py", line 250, in call
return self.commands[command_name].func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/command.py", line 303, in wrapper
return function(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/consoleaddons.py", line 551, in flowview_mode
raise exceptions.CommandError("Not viewing a flow.")
mitmproxy.exceptions.CommandError: Not viewing a flow.
```
#### System Information
Paste the output of "mitmproxy --version" here.
Tested with the following:
```
Mitmproxy: 8.0.0
Python: 3.8.10
OpenSSL: OpenSSL 1.1.1n 15 Mar 2022
Platform: macOS-10.16-x86_64-i386-64bit
```
and
```
Mitmproxy: 9.0.0.dev (+153, commit 5e7f3c8)
Python: 3.10.2
OpenSSL: OpenSSL 3.0.2 15 Mar 2022
Platform: macOS-12.3.1-x86_64-i386-64bit
```
Reloading a script with a custom view fails with "CommandError: Not viewing a flow."
#### Problem Description
Hot-reloading a script with a custom View doesn't work after any flow has been viewed. The reload crashes with an exception and the view is not loaded.
#### Steps to reproduce the behavior:
1. Create a script `test.py` with the following contents:
```python
from mitmproxy import contentviews, ctx, flow, http
from mitmproxy.contentviews.base import format_text
import typing
class TestView(contentviews.View):
name = "Test"
def __call__(self, data, **metadata):
return "Test HTML", format_text(data)
def render_priority(self, data: bytes, *, content_type: typing.Optional[str] = None, **metadata) -> float:
return float(data.startswith(b'<!')) * 2
def load(self, l):
contentviews.add(self)
def done(self):
contentviews.remove(self)
addons = [
TestView(),
]
```
2. Launch `mitmproxy` as `mitmproxy -s test.py`
3. Browse to `example.com` (e.g. `http_proxy=localhost:8080 curl example.com`).
4. A request should appear in mitmproxy. Open the request view, then return back to the main request list.
5. Make any edit to the `test.py` file and save.
6. An error appears in the error log:
```
error: Addon error: Traceback (most recent call last):
File "test.py", line 16, in load
contentviews.add(self)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/contentviews/__init__.py", line 52, in add
on_add.send(view)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/blinker/base.py", line 266, in send
return [(receiver, receiver(sender, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/blinker/base.py", line 266, in <listcomp>
return [(receiver, receiver(sender, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/flowview.py", line 66, in contentview_added
self.show()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/tabs.py", line 73, in show
body = self.tabs[self.tab_offset % len(self.tabs)][1](),
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/flowview.py", line 122, in view_request
return self.conn_text(flow.request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/flowview.py", line 326, in conn_text
viewmode = self.master.commands.call("console.flowview.mode")
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/command.py", line 250, in call
return self.commands[command_name].func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/command.py", line 303, in wrapper
return function(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mitmproxy/tools/console/consoleaddons.py", line 551, in flowview_mode
raise exceptions.CommandError("Not viewing a flow.")
mitmproxy.exceptions.CommandError: Not viewing a flow.
```
#### System Information
Paste the output of "mitmproxy --version" here.
Tested with the following:
```
Mitmproxy: 8.0.0
Python: 3.8.10
OpenSSL: OpenSSL 1.1.1n 15 Mar 2022
Platform: macOS-10.16-x86_64-i386-64bit
```
and
```
Mitmproxy: 9.0.0.dev (+153, commit 5e7f3c8)
Python: 3.10.2
OpenSSL: OpenSSL 3.0.2 15 Mar 2022
Platform: macOS-12.3.1-x86_64-i386-64bit
```
| 2022-05-06T00:26:32 |
|
mitmproxy/mitmproxy | 5,325 | mitmproxy__mitmproxy-5325 | [
"5316"
] | c5628658800979a6da85f793833db7096573e8c0 | diff --git a/mitmproxy/proxy/layers/http/_upstream_proxy.py b/mitmproxy/proxy/layers/http/_upstream_proxy.py
--- a/mitmproxy/proxy/layers/http/_upstream_proxy.py
+++ b/mitmproxy/proxy/layers/http/_upstream_proxy.py
@@ -46,12 +46,13 @@ def start_handshake(self) -> layer.CommandGenerator[None]:
return (yield from super().start_handshake())
assert self.conn.address
flow = http.HTTPFlow(self.context.client, self.tunnel_connection)
+ authority = self.conn.address[0].encode("idna") + f":{self.conn.address[1]}".encode()
flow.request = http.Request(
host=self.conn.address[0],
port=self.conn.address[1],
method=b"CONNECT",
scheme=b"",
- authority=f"{self.conn.address[0]}:{self.conn.address[1]}".encode(),
+ authority=authority,
path=b"",
http_version=b"HTTP/1.1",
headers=http.Headers(),
| diff --git a/test/mitmproxy/proxy/layers/http/test_http.py b/test/mitmproxy/proxy/layers/http/test_http.py
--- a/test/mitmproxy/proxy/layers/http/test_http.py
+++ b/test/mitmproxy/proxy/layers/http/test_http.py
@@ -722,8 +722,9 @@ def test_server_aborts(tctx, data):
@pytest.mark.parametrize("redirect", ["", "change-destination", "change-proxy"])
[email protected]("domain", [b"example.com", b"xn--eckwd4c7c.xn--zckzah"])
@pytest.mark.parametrize("scheme", ["http", "https"])
-def test_upstream_proxy(tctx, redirect, scheme):
+def test_upstream_proxy(tctx, redirect, domain, scheme):
"""Test that an upstream HTTP proxy is used."""
server = Placeholder(Server)
server2 = Placeholder(Server)
@@ -736,28 +737,28 @@ def test_upstream_proxy(tctx, redirect, scheme):
playbook
>> DataReceived(
tctx.client,
- b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\n\r\n",
+ b"GET http://%s/ HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
)
<< OpenConnection(server)
>> reply(None)
<< SendData(
- server, b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\n\r\n"
+ server, b"GET http://%s/ HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
)
)
else:
assert (
playbook
- >> DataReceived(tctx.client, b"CONNECT example.com:443 HTTP/1.1\r\n\r\n")
+ >> DataReceived(tctx.client, b"CONNECT %s:443 HTTP/1.1\r\n\r\n" % domain)
<< SendData(tctx.client, b"HTTP/1.1 200 Connection established\r\n\r\n")
- >> DataReceived(tctx.client, b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
+ >> DataReceived(tctx.client, b"GET / HTTP/1.1\r\nHost: %s\r\n\r\n" % domain)
<< layer.NextLayerHook(Placeholder())
>> reply_next_layer(lambda ctx: http.HttpLayer(ctx, HTTPMode.transparent))
<< OpenConnection(server)
>> reply(None)
- << SendData(server, b"CONNECT example.com:443 HTTP/1.1\r\n\r\n")
+ << SendData(server, b"CONNECT %s:443 HTTP/1.1\r\n\r\n" % domain)
>> DataReceived(server, b"HTTP/1.1 200 Connection established\r\n\r\n")
- << SendData(server, b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
+ << SendData(server, b"GET / HTTP/1.1\r\nHost: %s\r\n\r\n" % domain)
)
playbook >> DataReceived(server, b"HTTP/1.1 418 OK\r\nContent-Length: 0\r\n\r\n")
@@ -769,17 +770,17 @@ def test_upstream_proxy(tctx, redirect, scheme):
if scheme == "http":
playbook >> DataReceived(
tctx.client,
- b"GET http://example.com/two HTTP/1.1\r\nHost: example.com\r\n\r\n",
+ b"GET http://%s/two HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
)
else:
playbook >> DataReceived(
- tctx.client, b"GET /two HTTP/1.1\r\nHost: example.com\r\n\r\n"
+ tctx.client, b"GET /two HTTP/1.1\r\nHost: %s\r\n\r\n" % domain
)
assert playbook << http.HttpRequestHook(flow)
if redirect == "change-destination":
- flow().request.host = "other-server"
- flow().request.host_header = "example.com"
+ flow().request.host = domain + b".test"
+ flow().request.host_header = domain
elif redirect == "change-proxy":
flow().server_conn.via = ServerSpec("http", address=("other-proxy", 1234))
playbook >> reply()
@@ -796,25 +797,25 @@ def test_upstream_proxy(tctx, redirect, scheme):
if redirect == "change-destination":
playbook << SendData(
server2,
- b"GET http://other-server/two HTTP/1.1\r\nHost: example.com\r\n\r\n",
+ b"GET http://%s.test/two HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
)
else:
playbook << SendData(
server2,
- b"GET http://example.com/two HTTP/1.1\r\nHost: example.com\r\n\r\n",
+ b"GET http://%s/two HTTP/1.1\r\nHost: %s\r\n\r\n" % (domain, domain),
)
else:
if redirect == "change-destination":
- playbook << SendData(server2, b"CONNECT other-server:443 HTTP/1.1\r\n\r\n")
+ playbook << SendData(server2, b"CONNECT %s.test:443 HTTP/1.1\r\n\r\n" % domain)
playbook >> DataReceived(
server2, b"HTTP/1.1 200 Connection established\r\n\r\n"
)
elif redirect == "change-proxy":
- playbook << SendData(server2, b"CONNECT example.com:443 HTTP/1.1\r\n\r\n")
+ playbook << SendData(server2, b"CONNECT %s:443 HTTP/1.1\r\n\r\n" % domain)
playbook >> DataReceived(
server2, b"HTTP/1.1 200 Connection established\r\n\r\n"
)
- playbook << SendData(server2, b"GET /two HTTP/1.1\r\nHost: example.com\r\n\r\n")
+ playbook << SendData(server2, b"GET /two HTTP/1.1\r\nHost: %s\r\n\r\n" % domain)
playbook >> DataReceived(server2, b"HTTP/1.1 418 OK\r\nContent-Length: 0\r\n\r\n")
playbook << SendData(tctx.client, b"HTTP/1.1 418 OK\r\nContent-Length: 0\r\n\r\n")
@@ -822,9 +823,9 @@ def test_upstream_proxy(tctx, redirect, scheme):
assert playbook
if redirect == "change-destination":
- assert flow().server_conn.address[0] == "other-server"
+ assert flow().server_conn.address[0] == (domain + b".test").decode("idna")
else:
- assert flow().server_conn.address[0] == "example.com"
+ assert flow().server_conn.address[0] == domain.decode("idna")
if redirect == "change-proxy":
assert (
| Improper handling of Punycode
#### Problem Description
Can't open an address like `https://стопкоронавирус.рф/` through `mitmproxy` or other applications. My upstream proxy receives a CONNECT request to https://стопкоронавирус.СЂС„:443 instead. As the current run of `mitmproxy` was supposed to be just a test, it was configured only to forward all requests as-is to the upstream proxy, so this rules out any and all issues that could arise from my tinkering. Note: the actual URL that the browser opens is `https://xn--80aesfpebagmfblc0a.xn--p1ai` in this case.
Did it fail to properly encode the resulting authority? My upstream proxy normally has no issues with opening Puny-encoded URLs. I can verify that by opening that URL bypassing `mitmproxy`. It looks like it uses the wrong encoding, as it reminds me of the time when Unicode was not widespread and so this is how text in Russian would display when the text encoding wasn't set correctly.
#### Steps to reproduce the behavior:
1. Configure `mitmproxy` to forward all requests as-is to the upstream proxy that optionally can report what requests it receives. This includes no HTTPS decryption.
2. Navigate your browser to `https://стопкоронавирус.рф/`.
3. Check what the authority part of the URL the upstream proxy gets, it should be mangled.
#### System Information
Paste the output of "mitmproxy --version" here.
```Mitmproxy: 8.0.0 binary
Python: 3.10.2
OpenSSL: OpenSSL 1.1.1n 15 Mar 2022
Platform: Windows-10-10.0.19043-SP0
```
| Repro:
```
mitmdump
mitmdump --mode upstream:https://localhost:8080 -p 8081 --set ssl_insecure
curl -x localhost:8081 -k https://стопкоронавирус.рф/
``` | 2022-05-06T02:05:45 |
mitmproxy/mitmproxy | 5,342 | mitmproxy__mitmproxy-5342 | [
"5337",
"5337"
] | 362c1905625a2876dea845d60a2a0e5b6a0b7496 | diff --git a/mitmproxy/proxy/layers/http/_http1.py b/mitmproxy/proxy/layers/http/_http1.py
--- a/mitmproxy/proxy/layers/http/_http1.py
+++ b/mitmproxy/proxy/layers/http/_http1.py
@@ -348,6 +348,12 @@ def send(self, event: HttpEvent) -> layer.CommandGenerator[None]:
if "Host" not in request.headers and request.authority:
request.headers.insert(0, "Host", request.authority)
request.authority = ""
+ cookie_headers = request.headers.get_all("Cookie")
+ if len(cookie_headers) > 1:
+ # Only HTTP/2 supports multiple cookie headers, HTTP/1.x does not.
+ # see: https://www.rfc-editor.org/rfc/rfc6265#section-5.4
+ # https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.5
+ request.headers["Cookie"] = "; ".join(cookie_headers)
raw = http1.assemble_request_head(request)
yield commands.SendData(self.conn, raw)
elif isinstance(event, RequestData):
| diff --git a/test/mitmproxy/proxy/layers/http/test_http_version_interop.py b/test/mitmproxy/proxy/layers/http/test_http_version_interop.py
--- a/test/mitmproxy/proxy/layers/http/test_http_version_interop.py
+++ b/test/mitmproxy/proxy/layers/http/test_http_version_interop.py
@@ -11,12 +11,20 @@
from mitmproxy.proxy.layers import http
from test.mitmproxy.proxy.layers.http.hyper_h2_test_helpers import FrameFactory
from test.mitmproxy.proxy.layers.http.test_http2 import (
- example_request_headers,
example_response_headers,
make_h2,
)
from test.mitmproxy.proxy.tutils import Placeholder, Playbook, reply
+example_request_headers = (
+ (b":method", b"GET"),
+ (b":scheme", b"http"),
+ (b":path", b"/"),
+ (b":authority", b"example.com"),
+ (b"cookie", "a=1"),
+ (b"cookie", "b=2"),
+)
+
h2f = FrameFactory()
@@ -69,7 +77,7 @@ def test_h2_to_h1(tctx):
>> reply()
<< OpenConnection(server)
>> reply(None)
- << SendData(server, b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
+ << SendData(server, b"GET / HTTP/1.1\r\nHost: example.com\r\ncookie: a=1; b=2\r\n\r\n")
>> DataReceived(server, b"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\n")
<< http.HttpResponseHeadersHook(flow)
>> reply()
| mitmproxy doesn't merge multiple Cookie headers when proxying HTTP/2 request to HTTP/1.1 server
#### Problem Description
when mitmproxy running as reverse-proxy mode, mitmproxy accepts HTTP/2 connection, even upstream is plain HTTP server (w/ HTTP 1.1).
in HTTP/2, multiple cookie header is allowed, but old HTTP/1.x isn't. so we should merge multiple Cookie headers to one header when proxying to HTTP/1.1 server (see https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.5 https://www.rfc-editor.org/rfc/rfc6265#section-5.4 ), but mitmproxy isn't.

and actually some servers doesn't handle multiple Cookie headers on HTTP/1.x; so it causes mysterious bug (in my case, breaks Mastodon's sign-in).
#### Steps to reproduce the behavior:
1. Run mitmproxy as reverse-proxy mode, like `mitmproxy --mode=reverse:http://localhost -p 443 --certs fullchain-and-privkey.pem --set keep_host_header --modify-header '/x-forwarded-proto/https'`
2. Access to mitmproxy port with HTTPS, `https://localhost` and add some cookies
3. Check actual HTTP request by Wireshark or something (note: some servers are automatically handles multiple cookie headers even HTTP/1.1, like Node.js)
#### System Information
```
$ mitmproxy --version
Mitmproxy: 8.0.0
Python: 3.10.4
OpenSSL: OpenSSL 1.1.1o 3 May 2022
Platform: macOS-12.3.1-arm64-arm-64bit
```
(installed from Homebrew)
mitmproxy doesn't merge multiple Cookie headers when proxying HTTP/2 request to HTTP/1.1 server
#### Problem Description
when mitmproxy running as reverse-proxy mode, mitmproxy accepts HTTP/2 connection, even upstream is plain HTTP server (w/ HTTP 1.1).
in HTTP/2, multiple cookie header is allowed, but old HTTP/1.x isn't. so we should merge multiple Cookie headers to one header when proxying to HTTP/1.1 server (see https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.5 https://www.rfc-editor.org/rfc/rfc6265#section-5.4 ), but mitmproxy isn't.

and actually some servers doesn't handle multiple Cookie headers on HTTP/1.x; so it causes mysterious bug (in my case, breaks Mastodon's sign-in).
#### Steps to reproduce the behavior:
1. Run mitmproxy as reverse-proxy mode, like `mitmproxy --mode=reverse:http://localhost -p 443 --certs fullchain-and-privkey.pem --set keep_host_header --modify-header '/x-forwarded-proto/https'`
2. Access to mitmproxy port with HTTPS, `https://localhost` and add some cookies
3. Check actual HTTP request by Wireshark or something (note: some servers are automatically handles multiple cookie headers even HTTP/1.1, like Node.js)
#### System Information
```
$ mitmproxy --version
Mitmproxy: 8.0.0
Python: 3.10.4
OpenSSL: OpenSSL 1.1.1o 3 May 2022
Platform: macOS-12.3.1-arm64-arm-64bit
```
(installed from Homebrew)
| Thanks for the clear report! The relevant code that handles h2 -> h1 conversion is here:
https://github.com/mitmproxy/mitmproxy/blob/01a772ed4ee673307ba6b1eebfdeb5df65b13e99/mitmproxy/proxy/layers/http/_http1.py#L342-L350
I'd be happy to merge a PR that fixes this. 😃
Thanks for the clear report! The relevant code that handles h2 -> h1 conversion is here:
https://github.com/mitmproxy/mitmproxy/blob/01a772ed4ee673307ba6b1eebfdeb5df65b13e99/mitmproxy/proxy/layers/http/_http1.py#L342-L350
I'd be happy to merge a PR that fixes this. 😃 | 2022-05-12T16:54:14 |
mitmproxy/mitmproxy | 5,352 | mitmproxy__mitmproxy-5352 | [
"5343"
] | 4069830d4848c8f7114746bd598ba54a7b3c7b57 | 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
@@ -910,10 +910,9 @@ def event_to_child(
try:
stream = self.streams[command.event.stream_id]
except KeyError:
- # We may be getting errors for a specific stream even though we've already finished handling it.
- assert isinstance(
- command.event, (RequestProtocolError, ResponseProtocolError)
- )
+ # We may be getting data or errors for a stream even though we've already finished handling it,
+ # see for example https://github.com/mitmproxy/mitmproxy/issues/5343.
+ pass
else:
yield from self.event_to_child(stream, command.event)
elif isinstance(command, SendHttp):
| `test_fuzz_cancel` crashes for some inputs
From https://github.com/mitmproxy/mitmproxy/runs/6411486204:
```python
_______________________________ test_fuzz_cancel _______________________________
@given(stream_request=booleans(), stream_response=booleans(), data=data())
> def test_fuzz_cancel(stream_request, stream_response, data):
test/mitmproxy/proxy/layers/http/test_http_fuzz.py:420:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
test/mitmproxy/proxy/layers/http/test_http_fuzz.py:421: in test_fuzz_cancel
_test_cancel(
test/mitmproxy/proxy/layers/http/test_http_fuzz.py:526: in _test_cancel
assert playbook >> evt
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <test.mitmproxy.proxy.tutils.Playbook object at 0x1094a4ac0>
def __bool__(self):
"""Determine if playbook is correct."""
already_asserted = len(self.actual)
i = already_asserted
while i < len(self.expected):
x = self.expected[i]
if isinstance(x, commands.Command):
pass
else:
if hasattr(x, "playbook_eval"):
try:
x = self.expected[i] = x.playbook_eval(self)
except Exception:
self.actual.append(_TracebackInPlaybook(traceback.format_exc()))
break
for name, value in vars(x).items():
if isinstance(value, _Placeholder):
setattr(x, name, value())
if isinstance(x, events.OpenConnectionCompleted) and not x.reply:
x.command.connection.state = ConnectionState.OPEN
x.command.connection.timestamp_start = 1624544785
elif isinstance(x, events.ConnectionClosed):
x.connection.state &= ~ConnectionState.CAN_READ
x.connection.timestamp_end = 1624544787
self.actual.append(x)
cmds: list[commands.Command] = []
try:
# consume them one by one so that we can extend the log with all commands until traceback.
for cmd in self.layer.handle_event(x):
cmds.append(cmd)
except Exception:
self.actual.extend(cmds)
self.actual.append(_TracebackInPlaybook(traceback.format_exc()))
break
cmds = list(
_merge_sends(
cmds, ignore_hooks=not self.hooks, ignore_logs=not self.logs
)
)
self.actual.extend(cmds)
pos = len(self.actual) - len(cmds) - 1
hook_replies = []
for cmd in cmds:
pos += 1
assert self.actual[pos] == cmd
if isinstance(cmd, commands.CloseConnection):
if cmd.half_close:
cmd.connection.state &= ~ConnectionState.CAN_WRITE
else:
cmd.connection.state = ConnectionState.CLOSED
elif isinstance(cmd, commands.Log):
need_to_emulate_log = (
not self.logs
and cmd.level in ("debug", "info")
and (
pos >= len(self.expected)
or not isinstance(self.expected[pos], commands.Log)
)
)
if need_to_emulate_log:
self.expected.insert(pos, cmd)
elif isinstance(cmd, commands.StartHook) and not self.hooks:
need_to_emulate_hook = not self.hooks and (
pos >= len(self.expected)
or (
not (
isinstance(self.expected[pos], commands.StartHook)
and self.expected[pos].name == cmd.name
)
)
)
if need_to_emulate_hook:
self.expected.insert(pos, cmd)
if cmd.blocking:
# the current event may still have yielded more events, so we need to insert
# the reply *after* those additional events.
hook_replies.append(events.HookCompleted(cmd))
self.expected = (
self.expected[: pos + 1] + hook_replies + self.expected[pos + 1 :]
)
eq(
self.expected[i:], self.actual[i:]
) # compare now already to set placeholders
i += 1
if not eq(self.expected, self.actual):
self._errored = True
diffs = list(
difflib.ndiff(
[_fmt_entry(x) for x in self.expected],
[_fmt_entry(x) for x in self.actual],
)
)
if already_asserted:
diffs.insert(already_asserted, "==== asserted until here ====")
diff = "\n".join(diffs)
> raise AssertionError(f"Playbook mismatch!\n{diff}")
E AssertionError: Playbook mismatch!
E >> Start({})
E << SendData(client, b'\x00\x00*\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x10\x00\x00\x02\x00\x00\x00\x00\x00\x04\x00\x00\xff\xff\x00\x05\x00\x00@\x00\x00\x08\x00\x00\x00\x00\x00\x03\x00\x00\x00d\x00\x06\x00\x01\x00\x00')
E >> DataReceived(client, b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n')
E >> DataReceived(client, b'\x00\x00\x00\x04\x01\x00\x00\x00\x00')
E >> DataReceived(client, b'\x00\x00\r\x01\x04\x00\x00\x00\x01\x82\x86\x84A\x88/\x91\xd3]\x05\\\x87\xa7')
E << HttpRequestHeadersHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>)
E >> DataReceived(client, b'\x00\x00\x03\x00\x01\x00\x00\x00\x01foo')
E >> Reply(HttpRequestHeadersHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>), None)
E << OpenConnection({'connection': Server({'id': '…149a8d', 'address': ('example.com', 80), 'state': <ConnectionState.OPEN: 3>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_start': 1624544785})})
E >> Reply(OpenConnection({'connection': Server({'id': '…149a8d', 'address': ('example.com', 80), 'state': <ConnectionState.OPEN: 3>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_start': 1624544785})}), None)
E - << Log('Streaming request to example.com.', 'info')
E + << SendData(server, b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n\x00\x00*\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x10\x00\x00\x02\x00\x00\x00\x00\x00\x04\x00\x00\xff\xff\x00\x05\x00\x00@\x00\x00\x08\x00\x00\x00\x00\x00\x03\x00\x00\x00d\x00\x06\x00\x01\x00\x00\x00\x00\r\x01\x04\x00\x00\x00\x01\x82\x86\x84A\x88/\x91\xd3]\x05\\\x87\xa7\x00\x00\x03\x00\x00\x00\x00\x00\x01foo')
E << Log('Streaming request to example.com.', 'info')
E << HttpRequestHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>)
E >> DataReceived(server, b'\x00\x00\x01\x01\x04\x00\x00\x00\x01\x88')
E >> ConnectionClosed(connection=Client({'id': '…9d91e6', 'peername': ('client', 1234), 'sockname': ('127.0.0.1', 8080), 'timestamp_start': 1605699329, 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_end': 1624544787}))
E << CloseConnection({'connection': Client({'id': '…9d91e6', 'peername': ('client', 1234), 'sockname': ('127.0.0.1', 8080), 'timestamp_start': 1605699329, 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_end': 1624544787}), 'half_close': False})
E >> Reply(HttpRequestHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>), None)
E << SendData(server, b'\x00\x00\x00\x00\x01\x00\x00\x00\x01')
E << HttpResponseHeadersHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>)
E >> Reply(HttpResponseHeadersHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>), None)
E << HttpErrorHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>)
E ==== asserted until here ====
E >> Reply(HttpErrorHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E response = Response(200, no content)
E error = peer closed connection
E client_conn = Client(client:1234, state=closed, alpn=h2)
E server_conn = Server(example.com:80, state=open, alpn=h2)>), None)
E >> DataReceived(server, b'\x00\x00\x03\x00\x01\x00\x00\x00\x01bar')
E + << Traceback (most recent call last):
E File "/Users/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 911, in event_to_child
E stream = self.streams[command.event.stream_id]
E KeyError: 1
E
E During handling of the above exception, another exception occurred:
E
E Traceback (most recent call last):
E File "/Users/runner/work/mitmproxy/mitmproxy/test/mitmproxy/proxy/tutils.py", line 206, in __bool__
E for cmd in self.layer.handle_event(x):
E File "/Users/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layer.py", line 143, in handle_event
E command = command_generator.send(send)
E File "/Users/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 890, in _handle_event
E yield from self.event_to_child(handler, event)
E File "/Users/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 914, in event_to_child
E assert isinstance(
E AssertionError
test/mitmproxy/proxy/tutils.py:277: AssertionError
---------------------------------- Hypothesis ----------------------------------
Falsifying example: test_fuzz_cancel(
stream_request=True, stream_response=False, data=data(...),
)
Draw 1: ('data_req', DataReceived(client, b'\x00\x00\r\x01\x04\x00\x00\x00\x01\x82\x86\x84A\x88/\x91\xd3]\x05\\\x87\xa7'))
Draw 2: ('data_reqbody', DataReceived(client, b'\x00\x00\x03\x00\x01\x00\x00\x00\x01foo'))
Draw 3: ('reply_hook_req_headers', reply({'args': (), 'to': HttpRequestHeadersHook(flow=Placeholder:<HTTPFlow
request = Request(GET example.com:80/)
client_conn = Client(client:1234, state=open, alpn=h2)
server_conn = Server(<no address>, state=closed)>), 'side_effect': <function _test_cancel.<locals>.maybe_stream at 0x1091a3ac0>}))
Draw 4: ('reply_openconn', reply({'args': (None,), 'to': OpenConnection({'connection': Placeholder:Server({'id': '…149a8d', 'address': ('example.com', 80), 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp'})}), 'side_effect': <function make_h2 at 0x10878ac20>}))
Draw 5: ('data_resp', DataReceived(_placeholder, b'\x00\x00\x01\x01\x04\x00\x00\x00\x01\x88'))
Draw 6: ('err_client_disc', ConnectionClosed(connection=Client({'id': '…9d91e6', 'peername': ('client', 1234), 'sockname': ('127.0.0.1', 8080), 'timestamp_start': [1605](https://github.com/mitmproxy/mitmproxy/runs/6411486204?check_suite_focus=true#step:6:1605)699329, 'state': <ConnectionState.OPEN: 3>, 'transport_protocol': 'tcp', 'alpn': b'h2'})))
Draw 7: ('reply_hook_req', reply({'args': (), 'to': HttpRequestHook(flow=Placeholder:<HTTPFlow
request = Request(GET example.com:80/)
client_conn = Client(client:1234, state=closed, alpn=h2)
server_conn = Server(example.com:80, state=open, alpn=h2)>), 'side_effect': <function reply.<lambda> at 0x1086a7010>}))
Draw 8: ('reply_hook_resp_headers', reply({'args': (), 'to': HttpResponseHeadersHook(flow=Placeholder:<HTTPFlow
request = Request(GET example.com:80/)
response = Response(200, no content)
client_conn = Client(client:1234, state=closed, alpn=h2)
server_conn = Server(example.com:80, state=open, alpn=h2)>), 'side_effect': <function _test_cancel.<locals>.maybe_stream at 0x1091a3ac0>}))
Draw 9: ('reply_hook_error', reply({'args': (), 'to': HttpErrorHook(flow=Placeholder:<HTTPFlow
request = Request(GET example.com:80/)
response = Response(200, no content)
error = peer closed connection
client_conn = Client(client:1234, state=closed, alpn=h2)
server_conn = Server(example.com:80, state=open, alpn=h2)>), 'side_effect': <function reply.<lambda> at 0x1086a7010>}))
Draw 10: ('data_respbody', DataReceived(_placeholder, b'\x00\x00\x03\x00\x01\x00\x00\x00\x01bar'))
```
| Another one in https://github.com/mitmproxy/mitmproxy/runs/6442413613:
```python
E AssertionError: Playbook mismatch!
E >> Start({})
E << SendData(client, b'\x00\x00*\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x10\x00\x00\x02\x00\x00\x00\x00\x00\x04\x00\x00\xff\xff\x00\x05\x00\x00@\x00\x00\x08\x00\x00\x00\x00\x00\x03\x00\x00\x00d\x00\x06\x00\x01\x00\x00')
E >> DataReceived(client, b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n')
E >> DataReceived(client, b'\x00\x00\x00\x04\x01\x00\x00\x00\x00')
E >> DataReceived(client, b'\x00\x00\r\x01\x04\x00\x00\x00\x01\x82\x86\x84A\x88/\x91\xd3]\x05\\\x87\xa7')
E << HttpRequestHeadersHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E error = peer closed connection
E client_conn = Client(client:1234, state=open, alpn=h2)
E server_conn = Server(example.com:80, state=closed, alpn=h2)>)
E >> Reply(HttpRequestHeadersHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E error = peer closed connection
E client_conn = Client(client:1234, state=open, alpn=h2)
E server_conn = Server(example.com:80, state=closed, alpn=h2)>), None)
E << OpenConnection({'connection': Server({'id': '…75c3d4', 'address': ('example.com', 80), 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_start': 1624544785, 'timestamp_end': 1624544787})})
E >> Reply(OpenConnection({'connection': Server({'id': '…75c3d4', 'address': ('example.com', 80), 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_start': 1624544785, 'timestamp_end': 1624544787})}), None)
E - << Log('Streaming request to example.com.', 'info')
E + << SendData(server, b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n\x00\x00*\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x10\x00\x00\x02\x00\x00\x00\x00\x00\x04\x00\x00\xff\xff\x00\x05\x00\x00@\x00\x00\x08\x00\x00\x00\x00\x00\x03\x00\x00\x00d\x00\x06\x00\x01\x00\x00\x00\x00\r\x01\x04\x00\x00\x00\x01\x82\x86\x84A\x88/\x91\xd3]\x05\\\x87\xa7')
E << Log('Streaming request to example.com.', 'info')
E >> ConnectionClosed(connection=Server({'id': '…75c3d4', 'address': ('example.com', 80), 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_start': 1624544785, 'timestamp_end': 1624544787}))
E << CloseConnection({'connection': Server({'id': '…75c3d4', 'address': ('example.com', 80), 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_start': 1624544785, 'timestamp_end': 1624544787}), 'half_close': False})
E << HttpErrorHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E error = peer closed connection
E client_conn = Client(client:1234, state=open, alpn=h2)
E server_conn = Server(example.com:80, state=closed, alpn=h2)>)
E >> Reply(HttpErrorHook(flow=<HTTPFlow
E request = Request(GET example.com:80/)
E error = peer closed connection
E client_conn = Client(client:1234, state=open, alpn=h2)
E server_conn = Server(example.com:80, state=closed, alpn=h2)>), None)
E ==== asserted until here ====
E << SendData(client, b'\x00\x00\x1d\x01\x04\x00\x00\x00\x01H\x82l\x02v\x8e\xa4\xc9\xa6\xbb\x0f\xe7\xd2\x8f\xae\x05\xc0\xbc\x85\xef_\x87I|\xa5\x89\xd3M\x1f\x00\x00\x8e\x00\x01\x00\x00\x00\x01<html>\n<head>\n <title>502 Bad Gateway</title>\n</head>\n<body>\n <h1>502 Bad Gateway</h1>\n <p>peer closed connection</p>\n</body>\n</html>')
E >> DataReceived(client, b'\x00\x00\x03\x00\x01\x00\x00\x00\x01foo')
E + << Traceback (most recent call last):
E File "/home/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 911, in event_to_child
E stream = self.streams[command.event.stream_id]
E KeyError: 1
E
E During handling of the above exception, another exception occurred:
E
E Traceback (most recent call last):
E File "/home/runner/work/mitmproxy/mitmproxy/test/mitmproxy/proxy/tutils.py", line 206, in __bool__
E for cmd in self.layer.handle_event(x):
E File "/home/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layer.py", line 143, in handle_event
E command = command_generator.send(send)
E File "/home/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 890, in _handle_event
E yield from self.event_to_child(handler, event)
E File "/home/runner/work/mitmproxy/mitmproxy/mitmproxy/proxy/layers/http/__init__.py", line 914, in event_to_child
E assert isinstance(
E AssertionError
test/mitmproxy/proxy/tutils.py:277: AssertionError
---------------------------------- Hypothesis ----------------------------------
Falsifying example: test_fuzz_cancel(
stream_request=True, stream_response=False, data=data(...),
)
Draw 1: ('data_req', DataReceived(client, b'\x00\x00\r\x01\x04\x00\x00\x00\x01\x82\x86\x84A\x88/\x91\xd3]\x05\\\x87\xa7'))
Draw 2: ('reply_hook_req_headers', reply({'args': (), 'to': HttpRequestHeadersHook(flow=Placeholder:<HTTPFlow
request = Request(GET example.com:80/)
client_conn = Client(client:1234, state=open, alpn=h2)
server_conn = Server(<no address>, state=closed)>), 'side_effect': <function _test_cancel.<locals>.maybe_stream at 0x7f35d4734040>}))
Draw 3: ('reply_openconn', reply({'args': (None,), 'to': OpenConnection({'connection': Placeholder:Server({'id': '…75c3d4', 'address': ('example.com', 80), 'state': <ConnectionState.CLOSED: 0>, 'transport_protocol': 'tcp'})}), 'side_effect': <function make_h2 at 0x7f35d5c13b80>}))
Draw 4: ('err_server_disc', ConnectionClosed(connection=Placeholder:Server({'id': '…75c3d4', 'address': ('example.com', 80), 'state': <ConnectionState.OPEN: 3>, 'transport_protocol': 'tcp', 'alpn': b'h2', 'timestamp_start': 1624544785})))
Draw 5: ('reply_hook_error', reply({'args': (), 'to': HttpErrorHook(flow=Placeholder:<HTTPFlow
request = Request(GET example.com:80/)
error = peer closed connection
client_conn = Client(client:1234, state=open, alpn=h2)
server_conn = Server(example.com:80, state=closed, alpn=h2)>), 'side_effect': <function reply.<lambda> at 0x7f35d5f469d0>}))
Draw 6: ('data_reqbody', DataReceived(client, b'\x00\x00\x03\x00\x01\x00\x00\x00\x01foo'))
``` | 2022-05-15T20:12:56 |
|
mitmproxy/mitmproxy | 5,430 | mitmproxy__mitmproxy-5430 | [
"5428"
] | 3eab9f0856403c53871d258bba289dfcbeb6e0df | 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
@@ -117,9 +117,7 @@ def _handle_event(self, event: Event) -> CommandGenerator[None]:
elif isinstance(event, (RequestTrailers, ResponseTrailers)):
if self.is_open_for_us(event.stream_id):
trailers = [*event.trailers.fields]
- self.h2_conn.send_headers(
- event.stream_id, trailers, end_stream=True
- )
+ self.h2_conn.send_trailers(event.stream_id, trailers)
elif isinstance(event, (RequestEndOfMessage, ResponseEndOfMessage)):
if self.is_open_for_us(event.stream_id):
self.h2_conn.end_stream(event.stream_id)
diff --git a/mitmproxy/proxy/layers/http/_http_h2.py b/mitmproxy/proxy/layers/http/_http_h2.py
--- a/mitmproxy/proxy/layers/http/_http_h2.py
+++ b/mitmproxy/proxy/layers/http/_http_h2.py
@@ -1,5 +1,5 @@
import collections
-from typing import NamedTuple
+from typing import Dict, List, NamedTuple, Tuple
import h2.config
import h2.connection
@@ -34,10 +34,12 @@ class BufferedH2Connection(h2.connection.H2Connection):
"""
stream_buffers: collections.defaultdict[int, collections.deque[SendH2Data]]
+ stream_trailers: Dict[int, List[Tuple[bytes, bytes]]]
def __init__(self, config: h2.config.H2Configuration):
super().__init__(config)
self.stream_buffers = collections.defaultdict(collections.deque)
+ self.stream_trailers = {}
def send_data(
self,
@@ -77,7 +79,16 @@ def send_data(
# We can't send right now, so we buffer.
self.stream_buffers[stream_id].append(SendH2Data(data, end_stream))
- def end_stream(self, stream_id) -> None:
+ def send_trailers(self, stream_id: int, trailers: List[Tuple[bytes, bytes]]):
+ if self.stream_buffers.get(stream_id, None):
+ # Though trailers are not subject to flow control, we need to queue them and send strictly after data frames
+ self.stream_trailers[stream_id] = trailers
+ else:
+ self.send_headers(stream_id, trailers, end_stream=True)
+
+ def end_stream(self, stream_id: int) -> None:
+ if stream_id in self.stream_trailers:
+ return # we already have trailers queued up that will end the stream.
self.send_data(stream_id, b"", end_stream=True)
def reset_stream(self, stream_id: int, error_code: int = 0) -> None:
@@ -147,6 +158,8 @@ def stream_window_updated(self, stream_id: int) -> bool:
available_window -= len(chunk.data)
if not self.stream_buffers[stream_id]:
del self.stream_buffers[stream_id]
+ if stream_id in self.stream_trailers:
+ self.send_headers(stream_id, self.stream_trailers.pop(stream_id), end_stream=True)
sent_any_data = True
return sent_any_data
| diff --git a/test/mitmproxy/proxy/layers/http/test_http2.py b/test/mitmproxy/proxy/layers/http/test_http2.py
--- a/test/mitmproxy/proxy/layers/http/test_http2.py
+++ b/test/mitmproxy/proxy/layers/http/test_http2.py
@@ -288,6 +288,163 @@ def test_upstream_error(tctx):
assert b"server <> error" in d.data
[email protected]("trailers", ["trailers", ""])
+def test_long_response(tctx: Context, trailers):
+ playbook, cff = start_h2_client(tctx)
+ flow = Placeholder(HTTPFlow)
+ server = Placeholder(Server)
+ initial = Placeholder(bytes)
+ assert (
+ playbook
+ >> DataReceived(
+ tctx.client,
+ cff.build_headers_frame(
+ example_request_headers, flags=["END_STREAM"]
+ ).serialize(),
+ )
+ << http.HttpRequestHeadersHook(flow)
+ >> reply()
+ << http.HttpRequestHook(flow)
+ >> reply()
+ << OpenConnection(server)
+ >> reply(None, side_effect=make_h2)
+ << SendData(server, initial)
+ )
+ frames = decode_frames(initial())
+ assert [type(x) for x in frames] == [
+ hyperframe.frame.SettingsFrame,
+ hyperframe.frame.HeadersFrame,
+ ]
+ sff = FrameFactory()
+ assert (
+ playbook
+ # a conforming h2 server would send settings first, we disregard this for now.
+ >> DataReceived(
+ server, sff.build_headers_frame(example_response_headers).serialize()
+ )
+ << http.HttpResponseHeadersHook(flow)
+ >> reply()
+ >> DataReceived(
+ server,
+ sff.build_data_frame(b"a" * 10000, flags=[]).serialize()
+ )
+ >> DataReceived(
+ server,
+ sff.build_data_frame(b"a" * 10000, flags=[]).serialize(),
+ )
+ >> DataReceived(
+ server,
+ sff.build_data_frame(b"a" * 10000, flags=[]).serialize(),
+ )
+ >> DataReceived(
+ server,
+ sff.build_data_frame(b"a" * 10000, flags=[]).serialize(),
+ )
+ << SendData(
+ server,
+ sff.build_window_update_frame(0, 40000).serialize()
+ + sff.build_window_update_frame(1, 40000).serialize(),
+ )
+ >> DataReceived(
+ server,
+ sff.build_data_frame(b"a" * 10000, flags=[]).serialize(),
+ )
+ >> DataReceived(
+ server,
+ sff.build_data_frame(b"a" * 10000, flags=[]).serialize(),
+ )
+ >> DataReceived(
+ server,
+ sff.build_data_frame(b"a" * 10000, flags=[]).serialize(),
+ )
+ )
+ if trailers:
+ (
+ playbook
+ >> DataReceived(
+ server,
+ sff.build_headers_frame(
+ example_response_trailers, flags=["END_STREAM"]
+ ).serialize(),
+ )
+ )
+ else:
+ (
+ playbook
+ >> DataReceived(
+ server,
+ sff.build_data_frame(
+ b'', flags=["END_STREAM"]
+ ).serialize(),
+ )
+ )
+ (
+ playbook
+ << http.HttpResponseHook(flow)
+ >> reply()
+ << SendData(
+ tctx.client,
+ cff.build_headers_frame(example_response_headers).serialize()
+ + cff.build_data_frame(b"a" * 16384).serialize(),
+ )
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(b"a" * 16384).serialize(),
+ )
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(b"a" * 16384).serialize(),
+ )
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(b"a" * 16383).serialize(),
+ )
+ >> DataReceived(
+ tctx.client,
+ cff.build_window_update_frame(0, 65535).serialize()
+ + cff.build_window_update_frame(1, 65535).serialize(),
+ )
+ )
+ if trailers:
+ assert (
+ playbook
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(b"a" * 1).serialize(),
+ )
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(b"a" * 4464).serialize()
+ )
+ << SendData(
+ tctx.client,
+ cff.build_headers_frame(
+ example_response_trailers, flags=["END_STREAM"]
+ ).serialize(),
+ )
+ )
+ else:
+ assert (
+ playbook
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(b"a" * 1).serialize(),
+ )
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(b"a" * 4464).serialize()
+ )
+ << SendData(
+ tctx.client,
+ cff.build_data_frame(
+ b"", flags=["END_STREAM"]
+ ).serialize(),
+ )
+ )
+ assert flow().request.url == "http://example.com/"
+ assert flow().response.text == "a" * 70000
+
+
@pytest.mark.parametrize("stream", ["stream", ""])
@pytest.mark.parametrize("when", ["request", "response"])
@pytest.mark.parametrize("how", ["RST", "disconnect", "RST+disconnect"])
| [grpc] mitmproxy corrupts huge (>65kb) responses
#### Problem Description
Grpc requests with huge responses fails with error `io.grpc.StatusException: INTERNAL: Encountered end-of-stream mid-frame` if mitmproxy is used. Requests succeed without mitmproxy.
In my case response was 200k bytes.
#### Steps to reproduce the behavior:
1. Just make any grpc request that produces huge response
#### System Information
Mitmproxy: 8.0.0
Python: 3.10.2
OpenSSL: OpenSSL 1.1.1n 15 Mar 2022
Platform: macOS-10.16-x86_64-i386-64bit
Mitmproxy: 9.0.0.dev (+13, commit 3eab9f0)
Python: 3.9.12
OpenSSL: OpenSSL 3.0.3 3 May 2022
Platform: macOS-10.16-x86_64-i386-64bit
| 2022-06-24T11:22:04 |
|
mitmproxy/mitmproxy | 5,476 | mitmproxy__mitmproxy-5476 | [
"5474"
] | 156089229f76a5a4b08c0ffd492abad2a93e64ac | diff --git a/mitmproxy/contentviews/grpc.py b/mitmproxy/contentviews/grpc.py
--- a/mitmproxy/contentviews/grpc.py
+++ b/mitmproxy/contentviews/grpc.py
@@ -951,7 +951,7 @@ def format_grpc(
@dataclass
class ViewConfig:
- parser_options: ProtoParser.ParserOptions = ProtoParser.ParserOptions()
+ parser_options: ProtoParser.ParserOptions = field(default_factory=ProtoParser.ParserOptions)
parser_rules: list[ProtoParser.ParserRule] = field(default_factory=list)
| ValueError: mutable default <class 'mitmproxy.contentviews.grpc.ProtoParser.ParserOptions'> for field parser_options is not allowed: use default_factory on python 3.11
#### Problem Description
mitmproxy fails to start throwing a `ValueError` exception:
```
ValueError: mutable default <class 'mitmproxy.contentviews.grpc.ProtoParser.ParserOptions'> for field parser_options is not allowed: use default_factory
```
#### Steps to reproduce the behavior:
1. Install mitmproxy 8.1.1 on Fedora rawhide (37)
2. run the binary
#### System Information
```
$ /usr/bin/mitmproxy --version
Traceback (most recent call last):
File "/usr/bin/mitmproxy", line 8, in <module>
sys.exit(mitmproxy())
^^^^^^^^^^^
File "/usr/lib/python3.11/site-packages/mitmproxy/tools/main.py", line 118, in mitmproxy
from mitmproxy.tools import console
File "/usr/lib/python3.11/site-packages/mitmproxy/tools/console/__init__.py", line 1, in <module>
from mitmproxy.tools.console import master
File "/usr/lib/python3.11/site-packages/mitmproxy/tools/console/master.py", line 26, in <module>
from mitmproxy.tools.console import consoleaddons
File "/usr/lib/python3.11/site-packages/mitmproxy/tools/console/consoleaddons.py", line 6, in <module>
from mitmproxy import contentviews
File "/usr/lib/python3.11/site-packages/mitmproxy/contentviews/__init__.py", line 23, in <module>
from . import (
File "/usr/lib/python3.11/site-packages/mitmproxy/contentviews/grpc.py", line 952, in <module>
@dataclass
^^^^^^^^^
File "/usr/lib64/python3.11/dataclasses.py", line 1221, in dataclass
return wrap(cls)
^^^^^^^^^
File "/usr/lib64/python3.11/dataclasses.py", line 1211, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib64/python3.11/dataclasses.py", line 959, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib64/python3.11/dataclasses.py", line 816, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'mitmproxy.contentviews.grpc.ProtoParser.ParserOptions'> for field parser_options is not allowed: use default_factory
```
| We don't officially support Python 3.11 yet, but thanks for the pointer! | 2022-07-22T21:16:29 |
|
mitmproxy/mitmproxy | 5,485 | mitmproxy__mitmproxy-5485 | [
"5482"
] | 6b6ec2983aaaf5783cbf1aa685e7079ea7d78374 | diff --git a/docs/scripts/api-render.py b/docs/scripts/api-render.py
--- a/docs/scripts/api-render.py
+++ b/docs/scripts/api-render.py
@@ -32,6 +32,7 @@
"mitmproxy.http",
"mitmproxy.net.server_spec",
"mitmproxy.proxy.context",
+ "mitmproxy.proxy.mode_specs",
"mitmproxy.proxy.server_hooks",
"mitmproxy.tcp",
"mitmproxy.tls",
@@ -51,7 +52,7 @@
if isinstance(module, Path):
continue
filename = f"api/{module.replace('.', '/')}.html"
- (api_content / f"{module}.md").write_text(
+ (api_content / f"{module}.md").write_bytes(
textwrap.dedent(
f"""
---
@@ -65,7 +66,7 @@
{{{{< readfile file="/generated/{filename}" >}}}}
"""
- )
+ ).encode()
)
(here / ".." / "src" / "content" / "addons-api.md").touch()
diff --git a/mitmproxy/flow.py b/mitmproxy/flow.py
--- a/mitmproxy/flow.py
+++ b/mitmproxy/flow.py
@@ -151,13 +151,11 @@ def __init__(
__types: dict[str, type["Flow"]] = {}
- @classmethod
- @property
- def type(cls) -> str:
- """The flow type, for example `http`, `tcp`, or `dns`."""
- return cls.__name__.removesuffix("Flow").lower()
+ type: ClassVar[str] # automatically derived from the class name in __init_subclass__
+ """The flow type, for example `http`, `tcp`, or `dns`."""
def __init_subclass__(cls, **kwargs):
+ cls.type = cls.__name__.removesuffix("Flow").lower()
Flow.__types[cls.type] = cls
def get_state(self):
diff --git a/mitmproxy/proxy/mode_specs.py b/mitmproxy/proxy/mode_specs.py
--- a/mitmproxy/proxy/mode_specs.py
+++ b/mitmproxy/proxy/mode_specs.py
@@ -15,6 +15,9 @@
ProxyMode.parse("reverse:example.com@invalid-port") # ValueError
+ RegularMode.parse("regular") # ok
+ RegularMode.parse("socks5") # ValueError
+
"""
from __future__ import annotations
@@ -27,7 +30,6 @@
from mitmproxy.coretypes.serializable import Serializable
from mitmproxy.net import server_spec
-
# Python 3.11: Use typing.Self
Self = TypeVar("Self", bound="ProxyMode")
@@ -39,45 +41,45 @@ class ProxyMode(Serializable, metaclass=ABCMeta):
which then does its own data validation.
"""
full_spec: str
+ """The full proxy mode spec as entered by the user."""
data: str
+ """The (raw) mode data, i.e. the part after the mode name."""
custom_listen_host: str | None
+ """A custom listen host, if specified in the spec."""
custom_listen_port: int | None
+ """A custom listen port, if specified in the spec."""
+ type: ClassVar[str] # automatically derived from the class name in __init_subclass__
+ """The unique name for this proxy mode, e.g. "regular" or "reverse"."""
+ default_port: ClassVar[int] = 8080
+ """
+ Default listen port of servers for this mode, see `ProxyMode.listen_port()`.
+ """
transport_protocol: ClassVar[Literal["tcp", "udp"]] = "tcp"
"""
- The transport protocol used by this mode. Used to detect multiple servers targeting the same proto+port.
+ The transport protocol used by this mode's server.
+ This information is used by the proxyserver addon to determine if two modes want to listen on the same address.
"""
- default_port: ClassVar[int] = 8080
- __modes: ClassVar[dict[str, type[ProxyMode]]] = {}
+ __types: ClassVar[dict[str, Type[ProxyMode]]] = {}
+
+ def __init_subclass__(cls, **kwargs):
+ cls.type = cls.__name__.removesuffix("Mode").lower()
+ assert cls.type not in ProxyMode.__types
+ ProxyMode.__types[cls.type] = cls
+
+ def __repr__(self):
+ return f"ProxyMode.parse({self.full_spec!r})"
@abstractmethod
def __post_init__(self) -> None:
"""Validation of data happens here."""
- def listen_host(self, default: str | None = None) -> str:
- if self.custom_listen_host is not None:
- return self.custom_listen_host
- elif default is not None:
- return default
- else:
- return ""
-
- def listen_port(self, default: int | None = None) -> int:
- if self.custom_listen_port is not None:
- return self.custom_listen_port
- elif default is not None:
- return default
- else:
- return self.default_port
-
- @classmethod
- @property
- def type(cls) -> str:
- return cls.__name__.removesuffix("Mode").lower()
-
@classmethod
@cache
def parse(cls: Type[Self], spec: str) -> Self:
+ """
+ Parse a proxy mode specification and return the corresponding `ProxyMode` instance.
+ """
head, _, listen_at = spec.rpartition("@")
if not head:
head = listen_at
@@ -102,7 +104,7 @@ def parse(cls: Type[Self], spec: str) -> Self:
port = None
try:
- mode_cls = ProxyMode.__modes[mode.lower()]
+ mode_cls = ProxyMode.__types[mode.lower()]
except KeyError:
raise ValueError(f"unknown mode")
@@ -116,10 +118,31 @@ def parse(cls: Type[Self], spec: str) -> Self:
custom_listen_port=port
)
- def __init_subclass__(cls, **kwargs):
- t = cls.type.lower()
- assert t not in ProxyMode.__modes
- ProxyMode.__modes[t] = cls
+ def listen_host(self, default: str | None = None) -> str:
+ """
+ Return the address a server for this mode should listen on. This can be either directly
+ specified in the spec or taken from a user-configured global default (`options.listen_host`).
+ By default, return an empty string to listen on all hosts.
+ """
+ if self.custom_listen_host is not None:
+ return self.custom_listen_host
+ elif default is not None:
+ return default
+ else:
+ return ""
+
+ def listen_port(self, default: int | None = None) -> int:
+ """
+ Return the port a server for this mode should listen on. This can be either directly
+ specified in the spec, taken from a user-configured global default (`options.listen_port`),
+ or from `ProxyMode.default_port`.
+ """
+ if self.custom_listen_port is not None:
+ return self.custom_listen_port
+ elif default is not None:
+ return default
+ else:
+ return self.default_port
@classmethod
def from_state(cls, state):
@@ -139,16 +162,21 @@ def _check_empty(data):
class RegularMode(ProxyMode):
+ """A regular HTTP(S) proxy that is interfaced with `HTTP CONNECT` calls (or absolute-form HTTP requests)."""
+
def __post_init__(self) -> None:
_check_empty(self.data)
class TransparentMode(ProxyMode):
+ """A transparent proxy, see https://docs.mitmproxy.org/dev/howto-transparent/"""
+
def __post_init__(self) -> None:
_check_empty(self.data)
class UpstreamMode(ProxyMode):
+ """A regular HTTP(S) proxy, but all connections are forwarded to a second upstream HTTP(S) proxy."""
scheme: Literal["http", "https"]
address: tuple[str, int]
@@ -161,6 +189,7 @@ def __post_init__(self) -> None:
class ReverseMode(ProxyMode):
+ """A reverse proxy. This acts like a normal server, but redirects all requests to a fixed target."""
scheme: Literal["http", "https", "tcp", "tls"]
address: tuple[str, int]
@@ -173,6 +202,7 @@ def __post_init__(self) -> None:
class Socks5Mode(ProxyMode):
+ """A SOCKSv5 proxy."""
default_port = 1080
def __post_init__(self) -> None:
@@ -180,6 +210,7 @@ def __post_init__(self) -> None:
class DnsMode(ProxyMode):
+ """A DNS server or proxy."""
default_port = 53
transport_protocol: ClassVar[Literal["tcp", "udp"]] = "udp"
scheme: Literal["dns"] # DoH, DoQ, ...
| diff --git a/test/mitmproxy/proxy/test_mode_specs.py b/test/mitmproxy/proxy/test_mode_specs.py
--- a/test/mitmproxy/proxy/test_mode_specs.py
+++ b/test/mitmproxy/proxy/test_mode_specs.py
@@ -12,6 +12,7 @@ def test_parse():
assert m.data == "https://example.com/"
assert m.custom_listen_host == "127.0.0.1"
assert m.custom_listen_port == 443
+ assert repr(m) == "ProxyMode.parse('reverse:https://example.com/@127.0.0.1:443')"
with pytest.raises(ValueError, match="unknown mode"):
ProxyMode.parse("flibbel")
| Make `ProxyMode` docs clickable
I'd like to the see properties (`full_spec` etc.). Or is this a pdoc issue?

| 2022-07-25T14:00:45 |
|
mitmproxy/mitmproxy | 5,589 | mitmproxy__mitmproxy-5589 | [
"5363"
] | d3fb9f43494359cc6dddccb56e63f02b8eb44fd2 | diff --git a/mitmproxy/net/udp.py b/mitmproxy/net/udp.py
--- a/mitmproxy/net/udp.py
+++ b/mitmproxy/net/udp.py
@@ -175,8 +175,12 @@ def __init__(
"""
self._transport = transport
self._remote_addr = remote_addr
- self._reader = reader
- self._closed = asyncio.Event() if reader is not None else None
+ if reader is not None:
+ self._reader = reader
+ self._closed = asyncio.Event()
+ else:
+ self._reader = None
+ self._closed = None
@property
def _protocol(self) -> DrainableDatagramProtocol | udp_wireguard.WireGuardDatagramTransport:
@@ -199,9 +203,15 @@ def close(self) -> None:
self._transport.close()
else:
self._closed.set()
- if self._reader is not None:
+ assert self._reader
self._reader.feed_eof()
+ def is_closing(self) -> bool:
+ if self._closed is None:
+ return self._transport.is_closing()
+ else:
+ return self._closed.is_set()
+
async def wait_closed(self) -> None:
if self._closed is None:
await self._protocol.wait_closed()
diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -367,7 +367,8 @@ def server_event(self, event: events.Event) -> None:
elif isinstance(command, commands.SendData):
writer = self.transports[command.connection].writer
assert writer
- writer.write(command.data)
+ if not writer.is_closing():
+ writer.write(command.data)
elif isinstance(command, commands.CloseConnection):
self.close_connection(command.connection, command.half_close)
elif isinstance(command, commands.StartHook):
@@ -393,7 +394,8 @@ def close_connection(
try:
writer = self.transports[connection].writer
assert writer
- writer.write_eof()
+ if not writer.is_closing():
+ writer.write_eof()
except OSError:
# if we can't write to the socket anymore we presume it completely dead.
connection.state = ConnectionState.CLOSED
| diff --git a/test/mitmproxy/net/test_udp.py b/test/mitmproxy/net/test_udp.py
--- a/test/mitmproxy/net/test_udp.py
+++ b/test/mitmproxy/net/test_udp.py
@@ -45,11 +45,16 @@ def handle_datagram(
server.resume_writing()
await server.drain()
+ assert not client_writer.is_closing()
+ assert not server_writer.is_closing()
+
assert await client_reader.read(MAX_DATAGRAM_SIZE) == b"msg4"
client_writer.close()
+ assert client_writer.is_closing()
await client_writer.wait_closed()
server_writer.close()
+ assert server_writer.is_closing()
await server_writer.wait_closed()
server.close()
| 'socket.send() raised exception.' on stderr
#### Problem Description
In a long-running session of mitmdump that captures traffic of all surfing on an iPad, standard error logs a bunch of
```
socket.send() raised exception.
```
Nothing else is logged. Subjectively every now and then this is logged a browser tab stalls on the iPad. Looking at where the message comes from (`asyncio/*_events.py`) I believe this is the result of a socket already being dead when the HTTP/2 PING is sent periodically.
It looks to me like asyncio is catching this exception but mitmproxy is not made aware that the server connection is actually dead. Trying to use the dead connection often enough results in this log message:
```
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
logger.warning('socket.send() raised exception.')
```
I do not see any method to query the status of `self._conn_lost` which would help fixing this.
#### System Information
Mitmproxy: 9.0.0.dev (+151, commit 46f01ad)
Python: 3.9.7
OpenSSL: OpenSSL 1.1.1n 15 Mar 2022
Platform: Linux-4.18.0-383.el8.x86_64-x86_64-with-glibc2.28
| I did some googling and issues like this show up in the bug tracker of various projects. I found this fix for the issue in one project:
https://github.com/ska-sa/aiokatcp/commit/200189687148ab63b79081d8cfd6c2c92277895c
I did a small modification to `mitmproxy/proxy/server.py` to see if this approach would be viable:
```
elif isinstance(command, commands.SendData):
writer = self.transports[command.connection].writer
assert writer
+ if writer.transport.is_closing():
+ self.log(f"XXX Write to closed connection {command.connection}")
writer.write(command.data)
elif isinstance(command, commands.CloseConnection):
self.close_connection(command.connection, command.half_close)
...
try:
writer = self.transports[connection].writer
assert writer
+ if writer.transport.is_closing():
+ self.log(f"XXX Eof for closed connection {connection}")
writer.write_eof()
except OSError:
```
I did get the above log entry for `writer.write` pretty quickly. The log entries for one connection with the above log entry looks like this:
```
192.168.0.10:49775: client connect
192.168.0.10:49775: server connect x.x.x.x:443
192.168.0.10:49775: half-closing Server(x.x.x.x:443, state=open, src_port=49486)
192.168.0.10:49775: XXX Write to closed connection Client(192.168.0.10:49775, state=can_write)
192.168.0.10:49775: client disconnect
192.168.0.10:49775: closing transports...
192.168.0.10:49775: server disconnect x.x.x.x:443
192.168.0.10:49775: transports closed!
```
Any suggestions if this test before the write is a good idea and whether to just not write if it is true or if this should trigger a flow kill?
Thanks again for the very nice report even though information is understandably limited at this time. :) Can you verify that this does not occur when disabling HTTP/2 keepalives?
Assuming it's that, we can do multiple things here:
1. Add the check you suggested. That seems reasonable to me.
2. Check if the connection state is still open when receiving a wakeup, and only then sending a ping. This seems equally reasonable, maybe even more clean.
3. Add a new `CancelWakeup` command to cancel the wakup requests when receiving a ConnectionClosed. Mentioned here for completeness, but this approach seems mostly overengineered.
I let this run for more than a day now and here is what I got:
- 150 x write() to closed client connection
- 3 x write() to closed server connection
- 1 x write_eol() to closed client connection
**All connections** that logged the messages were pass-through connections. This is probably also the reason why few other will see the original error message. I have quite a list of hosts and domains for which I just want pass-through, because I don't care (ads, tracking) or because of certificate pinning or TLS fingerprinting. Anybody who wants to reproduce the error may want to do so with a script like this:
```
def tls_clienthello(data: tls.ClientHelloData):
data.ignore_connection = True
```
So given that no higher protocol is involved it may be the best to just add the checks in the two locations in `server.py`, optionally only if the connection is pass-through, but I think adding it for all cases is safer. What I am not sure is that if `is_closing()` is true then the proxy is guaranteed to otherwise notice the closed connection and terminate the flow and both ends. It looks to me that way and just not doing the `write()` or `write_eol()` should be enough.
I didn't find any other occurrences of `write()` or `write_eol()` but maybe I wasn't thorough enough.
Followup: I got one 'socket.send() raised exception.' in the error log and there was one matching client connection that logged five times `XXX Write ...`. `LOG_THRESHOLD_FOR_CONNLOST_WRITES` is defined to be 5 in `asyncio/constants.py` so I am pretty sure that connection produced the error log entry. | 2022-09-15T12:43:55 |
mitmproxy/mitmproxy | 5,603 | mitmproxy__mitmproxy-5603 | [
"5522"
] | ec5a74cd0ecbf81315a440e1f3786ddc324d6871 | diff --git a/mitmproxy/tools/web/webaddons.py b/mitmproxy/tools/web/webaddons.py
--- a/mitmproxy/tools/web/webaddons.py
+++ b/mitmproxy/tools/web/webaddons.py
@@ -44,7 +44,7 @@ def open_browser(url: str) -> bool:
"macosx",
"wslview %s",
"gio",
- "x-www-browser %s",
+ "x-www-browser",
"gnome-open %s",
"xdg-open",
"google-chrome",
| libGL error when starting latest version of mitmweb 8.1.1 on Debian
#### Problem Description
I was using old version of mitmproxy 6.0.2 that I got installed from the debian unstable repository and it works just fine. then today I decided to download the latest version of mitmproxy 8.1.1 and I got the below errors immediately after I type in `./mitmweb`
```
Web server listening at http://127.0.0.1:8081/
Opening in existing browser session.
Proxy server listening at *:8080
libGL error: MESA-LOADER: failed to open crocus: /usr/lib/dri/crocus_dri.so: cannot open shared object file: No such file or directory (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: crocus
libGL error: MESA-LOADER: failed to open crocus: /usr/lib/dri/crocus_dri.so: cannot open shared object file: No such file or directory (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: crocus
libGL error: MESA-LOADER: failed to open swrast: /usr/lib/dri/swrast_dri.so: cannot open shared object file: No such file or directory (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: swrast
[5508:5508:0100/000000.622195:ERROR:angle_platform_impl.cc(43)] Display.cpp:992 (initialize): ANGLE Display::initialize error 12289: Could not create a backing OpenGL context.
[5508:5508:0100/000000.622454:ERROR:gl_surface_egl.cc(831)] EGL Driver message (Critical) eglInitialize: Could not create a backing OpenGL context.
[5508:5508:0100/000000.622599:ERROR:gl_surface_egl.cc(1353)] eglInitialize OpenGL failed with error EGL_NOT_INITIALIZED, trying next display type
[5508:5508:0100/000000.625277:ERROR:angle_platform_impl.cc(43)] Display.cpp:992 (initialize): ANGLE Display::initialize error 12289: Could not create a backing OpenGL context.
[5508:5508:0100/000000.625508:ERROR:gl_surface_egl.cc(831)] EGL Driver message (Critical) eglInitialize: Could not create a backing OpenGL context.
[5508:5508:0100/000000.625555:ERROR:gl_surface_egl.cc(1353)] eglInitialize OpenGLES failed with error EGL_NOT_INITIALIZED
[5508:5508:0100/000000.625654:ERROR:gl_ozone_egl.cc(23)] GLSurfaceEGL::InitializeOneOff failed.
```
And the URL at http://127.0.0.1:8081 loads just a blank page.
Note that I checked, and I have `libgl1-mesa-dri` package already installed.
#### Steps to reproduce the behavior:
1. download latest version of mitmproxy 8.1.1
2. open the terminal and type in `./mitmweb`
#### System Information
Paste the output of "./mitmproxy --version"
```
Mitmproxy: 8.1.1 binary
Python: 3.10.5
OpenSSL: OpenSSL 3.0.3 3 May 2022
Platform: Linux-5.18.0-3-amd64-x86_64-with-glibc2.34
```
I will include the output of mitmproxy of version 6.0.2 that I have installed on the same system as I noticed that Python and OpenSSL versions are different:
```
Mitmproxy: 6.0.2
Python: 3.10.6
OpenSSL: OpenSSL 3.0.5 5 Jul 2022
Platform: Linux-5.18.0-3-amd64-x86_64-with-glibc2.34
```
| These messages come from Chromium (or whatever browser mitmweb launched) and should be irrelevant. Try `mitmweb --no-web-open-browser` and then manually open http://127.0.0.1:8081/. Does it still show a blank page?
For me what's always happening is that `mitmweb` will launch a browser and the page will never load. If I open the page in a second browser it also doesn't load unless I close the original one. Then it loads. I've always just lived with it, but if you're seeing the same then we should improve that.
`mitmweb` loads correctly when I do this.
Thanks for confirming!
I see two things to do here:
1. Fix whatever is causing the initial page to not load (maybe we shouldn't open the link before tornado is ready to accept connections)
2. Silence the stdout of whatever browser we're launching
The relevant code is here: https://github.com/mitmproxy/mitmproxy/blob/6494e97e781a03bc4df99fdde5ab8d6f3c5e7e9c/mitmproxy/tools/web/webaddons.py#L30
Seems like the Linux install does not ship with xdg-open or something like that?
It seems like `b.open(url)` is blocking? Tornado will only respond to request when I exit the browser process.
https://stackoverflow.com/questions/1149233/how-to-resume-program-or-exit-after-opening-webbrowser
But this seems unrelated to the libGL logs, which I'm only seeing when the browser is launched via mitmweb. This looks funny
```
(search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
```
Or is `\$${ORIGIN}` correct?
Anyway, the browser still works despite these warning. But it blocks mitmweb.
I've managed to make the latest version work, I'm not sure why, but it wasn't working with Debian Sid, I reinstalled Debian Stable and now it's working as expected.
I thought I would add that _if_ my browser is already open, and I run `mitmweb`, it will open in a new tab as expected. This error only occurs for me when a browser is not running.
This sounds like a bug in Python's webbrowser module to me when there's no `x-www-browser`, `gnome-open`, or `xdg-open` binary on the system and we fall back to Chrome. See the code snippet I linked above.
I have both `x-www-browser` and `xdg-open`.
Check out what I get in the REPL
```
>>> webbrowser.get('x-www-browser %s')
<webbrowser.GenericBrowser object at 0x7fcce4da0160>
>>> webbrowser.get('x-www-browser')
<webbrowser.BackgroundBrowser object at 0x7fcce4ed3fa0>
```
I assume anything other than `BackgroundBrowser` is blocking? Why the `%s`? Why even have the array when
> If using is None, return a controller for a default browser appropriate to the caller’s environment.
> Why even have the array when
The default list includes stuff like `lynx`, which makes for a usability nightmare on server OSes. `x-www-browser` should probably not have the `%s`. If you can test this on your system, would you mind sending a PR?
(`%s` is needed for executables not natively supported by the webbrowser module) | 2022-09-22T15:30:55 |
|
mitmproxy/mitmproxy | 5,648 | mitmproxy__mitmproxy-5648 | [
"5623"
] | 42df073f7ec57360dff6f1a974c4d42464e43a81 | diff --git a/mitmproxy/contentviews/json.py b/mitmproxy/contentviews/json.py
--- a/mitmproxy/contentviews/json.py
+++ b/mitmproxy/contentviews/json.py
@@ -28,11 +28,14 @@ def format_json(data: Any) -> Iterator[base.TViewLine]:
yield current_line
current_line = []
if re.match(r'\s*"', chunk):
- current_line.append(("json_string", chunk))
+ if len(current_line) == 1 and current_line[0][0] == "text" and current_line[0][1].isspace():
+ current_line.append(("Token_Name_Tag", chunk))
+ else:
+ current_line.append(("Token_Literal_String", chunk))
elif re.match(r"\s*\d", chunk):
- current_line.append(("json_number", chunk))
+ current_line.append(("Token_Literal_Number", chunk))
elif re.match(r"\s*(true|null|false)", chunk):
- current_line.append(("json_boolean", chunk))
+ current_line.append(("Token_Keyword_Constant", chunk))
else:
current_line.append(("text", chunk))
yield current_line
diff --git a/mitmproxy/contentviews/msgpack.py b/mitmproxy/contentviews/msgpack.py
--- a/mitmproxy/contentviews/msgpack.py
+++ b/mitmproxy/contentviews/msgpack.py
@@ -15,23 +15,62 @@ def parse_msgpack(s: bytes) -> Any:
return PARSE_ERROR
-def pretty(value, htchar=" ", lfchar="\n", indent=0):
- nlch = lfchar + htchar * (indent + 1)
- if type(value) is dict:
- items = [
- nlch + repr(key) + ": " + pretty(value[key], htchar, lfchar, indent + 1)
- for key in value
- ]
- return "{%s}" % (",".join(items) + lfchar + htchar * indent)
- elif type(value) is list:
- items = [nlch + pretty(item, htchar, lfchar, indent + 1) for item in value]
- return "[%s]" % (",".join(items) + lfchar + htchar * indent)
- else:
- return repr(value)
+def format_msgpack(data: Any, output = None, indent_count: int = 0) -> list[base.TViewLine]:
+ if output is None:
+ output = [[]]
+
+ indent = ("text", " " * indent_count)
+
+ if type(data) is str:
+ token = [("Token_Literal_String", f"\"{data}\"")]
+ output[-1] += token
+
+ # Need to return if single value, but return is discarded in dict/list loop
+ return output
+
+ elif type(data) is float or type(data) is int:
+ token = [("Token_Literal_Number", repr(data))]
+ output[-1] += token
+
+ return output
+
+ elif type(data) is bool:
+ token = [("Token_Keyword_Constant", repr(data))]
+ output[-1] += token
+
+ return output
+
+ elif type(data) is dict:
+ output[-1] += [("text", "{")]
+ for key in data:
+ output.append([indent, ("text", " "), ("Token_Name_Tag", f'"{key}"'), ("text", ": ")])
+ format_msgpack(data[key], output, indent_count + 1)
+ if key != list(data)[-1]:
+ output[-1] += [("text", ",")]
+
+ output.append([indent, ("text", "}")])
+
+ return output
+
+ elif type(data) is list:
+ output[-1] += [("text", "[")]
+ for item in data:
+ output.append([indent, ("text", " ")])
+ format_msgpack(item, output, indent_count + 1)
+
+ if item != data[-1]:
+ output[-1] += [("text", ",")]
+
+ output.append([indent, ("text", "]")])
+
+ return output
+
+ else:
+ token = [("text", repr(data))]
+ output[-1] += token
-def format_msgpack(data):
- return base.format_text(pretty(data))
+ return output
class ViewMsgPack(base.View):
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
@@ -69,10 +69,11 @@ class Palette:
"mark",
# Hex view
"offset",
- # JSON view
- "json_string",
- "json_number",
- "json_boolean",
+ # JSON/msgpack view
+ "Token_Name_Tag",
+ "Token_Literal_String",
+ "Token_Literal_Number",
+ "Token_Keyword_Constant",
# TCP flow details
"from_client",
"to_client",
@@ -207,10 +208,11 @@ class LowDark(Palette):
mark=("light red", "default"),
# Hex view
offset=("dark cyan", "default"),
- # JSON view
- json_string=("dark blue", "default"),
- json_number=("light magenta", "default"),
- json_boolean=("dark magenta", "default"),
+ # JSON/msgpack view
+ Token_Name_Tag=("dark green", "default"),
+ Token_Literal_String=("dark blue", "default"),
+ Token_Literal_Number=("light magenta", "default"),
+ Token_Keyword_Constant=("dark magenta", "default"),
# TCP flow details
from_client=("light blue", "default"),
to_client=("light red", "default"),
@@ -306,10 +308,11 @@ class LowLight(Palette):
mark=("dark red", "default"),
# Hex view
offset=("dark blue", "default"),
- # JSON view
- json_string=("dark blue", "default"),
- json_number=("light magenta", "default"),
- json_boolean=("dark magenta", "default"),
+ # JSON/msgpack view
+ Token_Name_Tag=("dark green", "default"),
+ Token_Literal_String=("dark blue", "default"),
+ Token_Literal_Number=("light magenta", "default"),
+ Token_Keyword_Constant=("dark magenta", "default"),
# TCP flow details
from_client=("dark blue", "default"),
to_client=("dark red", "default"),
@@ -427,10 +430,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"),
+ # JSON/msgpack view
+ Token_Name_Tag=(sol_green, "default"),
+ Token_Literal_String=(sol_cyan, "default"),
+ Token_Literal_Number=(sol_blue, "default"),
+ Token_Keyword_Constant=(sol_magenta, "default"),
# TCP flow details
from_client=(sol_blue, "default"),
to_client=(sol_red, "default"),
@@ -506,10 +510,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"),
+ # JSON/msgpack view
+ Token_Name_Tag=(sol_green, "default"),
+ Token_Literal_String=(sol_cyan, "default"),
+ Token_Literal_Number=(sol_blue, "default"),
+ Token_Keyword_Constant=(sol_magenta, "default"),
# TCP flow details
from_client=(sol_blue, "default"),
to_client=(sol_red, "default"),
| 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
@@ -17,6 +17,32 @@ def test_parse_json():
def test_format_json():
assert list(json.format_json({"data": ["str", 42, True, False, None, {}, []]}))
+ assert list(json.format_json({"string": "test"})) == [
+ [('text', '{'), ('text', '')],
+ [('text', ' '), ('Token_Name_Tag', '"string"'), ('text', ': '), ('Token_Literal_String', '"test"'), ('text', '')],
+ [('text', ''), ('text', '}')]]
+ assert list(json.format_json({"num": 4})) == [
+ [('text', '{'), ('text', '')],
+ [('text', ' '), ('Token_Name_Tag', '"num"'), ('text', ': '), ('Token_Literal_Number', '4'), ('text', '')],
+ [('text', ''), ('text', '}')]]
+ assert list(json.format_json({"bool": True})) == [
+ [('text', '{'), ('text', '')],
+ [('text', ' '), ('Token_Name_Tag', '"bool"'), ('text', ': '), ('Token_Keyword_Constant', 'true'), ('text', '')],
+ [('text', ''), ('text', '}')]]
+ assert list(json.format_json({"object": {"int": 1}})) == [
+ [('text', '{'), ('text', '')],
+ [('text', ' '), ('Token_Name_Tag', '"object"'), ('text', ': '), ('text', '{'), ('text', '')],
+ [('text', ' '), ('Token_Name_Tag', '"int"'), ('text', ': '), ('Token_Literal_Number', '1'), ('text', '')],
+ [('text', ' '), ('text', '}'), ('text', '')],
+ [('text', ''), ('text', '}')]]
+ assert list(json.format_json({"list": ["string", 1, True]})) == [
+ [('text', '{'), ('text', '')],
+ [('text', ' '), ('Token_Name_Tag', '"list"'), ('text', ': '), ('text', '[')],
+ [('Token_Literal_String', ' "string"'), ('text', ',')],
+ [('Token_Literal_Number', ' 1'), ('text', ',')],
+ [('Token_Keyword_Constant', ' true'), ('text', '')],
+ [('text', ' '), ('text', ']'), ('text', '')],
+ [('text', ''), ('text', '}')]]
def test_view_json():
diff --git a/test/mitmproxy/contentviews/test_msgpack.py b/test/mitmproxy/contentviews/test_msgpack.py
--- a/test/mitmproxy/contentviews/test_msgpack.py
+++ b/test/mitmproxy/contentviews/test_msgpack.py
@@ -18,9 +18,32 @@ def test_parse_msgpack():
def test_format_msgpack():
- assert list(
- msgpack.format_msgpack({"data": ["str", 42, True, False, None, {}, []]})
- )
+ assert list(msgpack.format_msgpack({"string": "test", "int": 1, "float": 1.44, "bool": True})) == [
+ [('text', '{')],
+ [('text', ''), ('text', ' '), ('Token_Name_Tag', '"string"'), ('text', ': '), ('Token_Literal_String', '"test"'), ('text', ',')],
+ [('text', ''), ('text', ' '), ('Token_Name_Tag', '"int"'), ('text', ': '), ('Token_Literal_Number', '1'), ('text', ',')],
+ [('text', ''), ('text', ' '), ('Token_Name_Tag', '"float"'), ('text', ': '), ('Token_Literal_Number', '1.44'), ('text', ',')],
+ [('text', ''), ('text', ' '), ('Token_Name_Tag', '"bool"'), ('text', ': '), ('Token_Keyword_Constant', 'True')],
+ [('text', ''), ('text', '}')]
+ ]
+
+ assert list(msgpack.format_msgpack({"object": {"key": "value"}, "list": [1]})) == [
+ [('text', '{')],
+ [('text', ''), ('text', ' '), ('Token_Name_Tag', '"object"'), ('text', ': '), ('text', '{')],
+ [('text', ' '), ('text', ' '), ('Token_Name_Tag', '"key"'), ('text', ': '), ('Token_Literal_String', '"value"')],
+ [('text', ' '), ('text', '}'), ('text', ',')],
+ [('text', ''), ('text', ' '), ('Token_Name_Tag', '"list"'), ('text', ': '), ('text', '[')],
+ [('text', ' '), ('text', ' '), ('Token_Literal_Number', '1')],
+ [('text', ' '), ('text', ']')],
+ [('text', ''), ('text', '}')]]
+
+ assert list(msgpack.format_msgpack('string')) == [[('Token_Literal_String', '"string"')]]
+
+ assert list(msgpack.format_msgpack(1.2)) == [[('Token_Literal_Number', '1.2')]]
+
+ assert list(msgpack.format_msgpack(True)) == [[('Token_Keyword_Constant', 'True')]]
+
+ assert list(msgpack.format_msgpack(b'\x01\x02\x03')) == [[('text', "b'\\x01\\x02\\x03'")]]
def test_view_msgpack():
| mitmweb: Add support for syntax highlighting / coloring
#### Problem Description
When selecting "View: msgpack" on a msgpack request or response, the resultant JSON is displayed using single-quotes (`'`), which is not valid. It should use double-quotes (`"`) instead.
#### Steps to reproduce the behavior:
1. Have a request/response in `mitmweb` and click Replace and use the file contained in this archive: [get_resource_version.zip](https://github.com/mitmproxy/mitmproxy/files/9692381/get_resource_version.zip)
2. Select "View: msgpack" next to the Replace button
3. Notice that the resultant JSON contains single-quoted properties and strings:
```json
{
'data_headers': {
'result_code': 1
},
'data': {
'resource_version': 'y2XM6giU6zz56wCm'
}
}
```
I am not an expert on the JSON standard, but pasting the output into a [JSON validator](https://duckduckgo.com/?q=json+validator&t=ffab&ia=answer) throws up errors which can be fixed by using double quotes (and I assume that's what the red highlighting means, since the above code block starts with ```json)
#### System Information
```
>mitmproxy --version
Mitmproxy: 8.1.1
Python: 3.10.6
OpenSSL: OpenSSL 1.1.1n 15 Mar 2022
Platform: Windows-10-10.0.22622-SP0
```
#### P.S.
I know a bit of Python but am unfamiliar with this codebase, however I would be happy to try fixing this myself and submitting a PR if that would be easier? It seems like something that would be simple enough for a first time contributor to attempt.
| I don't know if this is _supposed_ to be valid JSON. First and foremost this is a human readable version of msgpack that happens to look somewhat like JSON.
The code is here
https://github.com/mitmproxy/mitmproxy/blob/a1631154d722ea4c82dcb72e0c84ad38c6991de5/mitmproxy/contentviews/msgpack.py#L18-L30
I don't know if everything that msgpack does _can_ be represented in JSON (e.g. bytes). If so, then this code could basically just use `json.dumps`.
@tasn can you comment on that please?
So yeah, msgpack is _not_ JSON compatible. E.g. map keys can have _any_ type. I'm closing, feel free to re-open if I'm missing something.
Ah, that makes sense about them not being the same especially with the bytes.
My use case was more pasting them into syntax highlighting things which expect the double quotes, rather than parsing the json (there are msgpack deserialisers for that). My msgpack data usually only used primitive types. I can just continue using a simple find-and-replace though, so I don’t have any objection to you closing.
If you're interested in contributing, I'm sure adding coloring to the mspack view would be a great addition.
https://github.com/mitmproxy/mitmproxy/blob/a1631154d722ea4c82dcb72e0c84ad38c6991de5/mitmproxy/contentviews/msgpack.py#L18-L30
Here's how this works for JSON
https://github.com/mitmproxy/mitmproxy/blob/a1631154d722ea4c82dcb72e0c84ad38c6991de5/mitmproxy/contentviews/json.py#L20-L38
You essentially need to use `TViewLine` and mostly in the last else add tokens for the corresponding types instead of treating all the same:
https://github.com/mitmproxy/mitmproxy/blob/a1631154d722ea4c82dcb72e0c84ad38c6991de5/mitmproxy/contentviews/msgpack.py#L29-L30
But mitmweb is currently missing the colors that the terminal uses https://github.com/mitmproxy/mitmproxy/blob/cd4a74fae7cbd8119afc3900597f798ec1604db7/mitmproxy/tools/console/palettes.py#L149-L225
That should be somewhat easy to add as well, but it can be a separate step. (TIL mitmproxy has themes?)
I'm going to re-open this but as a feature request to add syntax highlighting support to mitmweb. Everything is already there (e.g. it adds things like `class="json_string"`) but it doesn't do anything yet. So if the classes/colors where there it would already work for JSON. For msgpack it lacks it in the contentview.
@Prinzhorn, yeah, adding coloring would indeed be a great addition!
As for JSON: yeah, msgpack is more complex than JSON and you can't represent it as valid json.
I’m happy to contribute syntax highlighting as described. Thank you for taking the time to provide the relevant code snippets. I have a fair bit on my plate right now so it might be a while before I have a chance to look at it.
I think I understand roughly what needs to be done, but one question I had was how this would be tested — can you actually get data from the content view with colour information inside of it? Or would it be a screenshot test?
> how this would be tested — can you actually get data from the content view with colour information inside of it? Or would it be a screenshot test?
Check out the tests for other contentviews https://github.com/mitmproxy/mitmproxy/tree/a1631154d722ea4c82dcb72e0c84ad38c6991de5/test/mitmproxy/contentviews
From what I can tell none of them test the coloring @mhils ?
If you wanted to test the coloring, you should be able to test the output of `pretty` for different inputs and make sure the expected parts have the expected tokens (strings, numbers, etc.)
Also again I think there are two separate things to be done:
1. Add coloring to the msgpack view by using `TViewLine` and adding the appropriate tokens to the list (strings, numbers, etc.)
2. Make coloring work in mitmweb. In general mitmweb already adds `<span>`s with the token classes already. But I don't know what's the best way to get the colors into mitmweb without doing it manually.
> From what I can tell none of them test the coloring @mhils ?
I don't think so, but I haven't checked. :)
> Make coloring work in mitmweb. In general mitmweb already adds <span>s with the token classes already. But I don't know what's the best way to get the colors into mitmweb without doing it manually.
Common tokens have CSS class equivalents already (and we can add more there). Let me know if that doesn't make sense! :) | 2022-10-14T23:23:15 |
mitmproxy/mitmproxy | 5,659 | mitmproxy__mitmproxy-5659 | [
"5405"
] | 435bd4af18b1d23dc747e861440e53f28568d258 | 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
@@ -280,7 +280,7 @@ def open(self):
self.connections.add(self)
def on_close(self):
- self.connections.remove(self)
+ self.connections.discard(self)
@classmethod
def broadcast(cls, **kwargs):
@@ -288,12 +288,16 @@ def broadcast(cls, **kwargs):
"utf8", "surrogateescape"
)
+ errored = []
for conn in cls.connections:
try:
if not conn.ws_connection.is_closing():
conn.write_message(message)
except Exception: # pragma: no cover
- logging.error("Error sending message", exc_info=True)
+ logging.debug("Error sending WebSocket message.", exc_info=True)
+ errored.append(conn) # workaround for https://github.com/tornadoweb/tornado/issues/2958
+ for conn in errored:
+ cls.connections.remove(conn)
class ClientConnection(WebSocketEventBroadcaster):
| tornado.iostream.StreamClosedError
#### Problem Description
I honestly have no idea. The terminal popped an error message saying:
```python
Traceback (most recent call last):
File "/opt/homebrew/Cellar/mitmproxy/8.1.0/libexec/lib/python3.10/site-packages/tornado/websocket.py", line 1102, in wrapper
await fut
tornado.iostream.StreamClosedError: Stream is closed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/homebrew/Cellar/mitmproxy/8.1.0/libexec/lib/python3.10/site-packages/tornado/websocket.py", line 1104, in wrapper
raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError
Please lodge a bug report at:
https://github.com/mitmproxy/mitmproxy/issues
```
and I thought I'll be a good citizen and report the error.
#### Steps to reproduce the behavior:
1.
2.
3.
#### System Information
Mitmproxy: 8.1.0
Python: 3.10.4
OpenSSL: OpenSSL 1.1.1o 3 May 2022
Platform: macOS-12.4-arm64-arm-64bit
<img width="1624" alt="Screenshot 2022-06-08 at 15 33 53" src="https://user-images.githubusercontent.com/75550932/172617337-6dffe0c3-0d9b-430e-a92b-31b6897f1b7c.png">
| I was able to reproduce this once but not consistently. I had two browsers open at `8081`, then opening a browser that proxied a website with lot of requests and then closed one of the mitmweb clients. It actually looked like this:
```
// hundreds more of these
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
tornado.websocket.WebSocketClosedError
[::1]:39066: client disconnect
[::1]:39068: client disconnect
[::1]:39070: client disconnect
[::1]:39074: client disconnect
[::1]:39076: client disconnect
Traceback (most recent call last):
File "tornado/websocket.py", line 1102, in wrapper
tornado.iostream.StreamClosedError: Stream is closed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "tornado/websocket.py", line 1104, in wrapper
tornado.websocket.WebSocketClosedError
Please lodge a bug report at:
https://github.com/mitmproxy/mitmproxy/issues
```
I think this is a matter of mitmweb not properly keeping track of WebSockets and trying to write to closed ones.
After doing some digging this might as well be caused by an upstream bug https://github.com/tornadoweb/tornado/issues/2958 which would cause the WebSocket to never be removed from the set:
https://github.com/mitmproxy/mitmproxy/blob/73c38f698d42002947e46294498b2166f3139cf4/mitmproxy/tools/web/app.py#L275-L283
Honestly it feels like we should just swallow the error in `broadcast` [here](https://github.com/mitmproxy/mitmproxy/blob/73c38f698d42002947e46294498b2166f3139cf4/mitmproxy/tools/web/app.py#L292-L295) and be done with it.
> Honestly it feels like we should just swallow the error in `broadcast` [here](https://github.com/mitmproxy/mitmproxy/blob/73c38f698d42002947e46294498b2166f3139cf4/mitmproxy/tools/web/app.py#L292-L295) and be done with it.
And also `if closedError: self.connections.remove(self)` :eyes: ?
But I think that would only get rid of the
```
ERROR:root:Error sending message
Traceback (most recent call last):
File "mitmproxy/tools/web/app.py", line 292, in broadcast
File "tornado/websocket.py", line 337, in write_message
```
and not the _uncaught_ exception? I don't know where that originates though.
Also seeing this if I make a large number of requests (like a load test). | 2022-10-19T15:27:20 |
|
mitmproxy/mitmproxy | 5,695 | mitmproxy__mitmproxy-5695 | [
"4669"
] | 0f53caee7d886b76279cbdb57cc3e1a325e38792 | diff --git a/mitmproxy/addons/termlog.py b/mitmproxy/addons/termlog.py
--- a/mitmproxy/addons/termlog.py
+++ b/mitmproxy/addons/termlog.py
@@ -51,7 +51,9 @@ def __init__(
self.formatter = log.MitmFormatter(self.has_vt_codes)
def emit(self, record: logging.LogRecord) -> None:
- print(
- self.format(record),
- file=self.file
- )
+ try:
+ print(self.format(record), file=self.file)
+ except OSError:
+ # We cannot print, exit immediately.
+ # See https://github.com/mitmproxy/mitmproxy/issues/4669
+ sys.exit(1)
| diff --git a/test/mitmproxy/addons/test_termlog.py b/test/mitmproxy/addons/test_termlog.py
--- a/test/mitmproxy/addons/test_termlog.py
+++ b/test/mitmproxy/addons/test_termlog.py
@@ -1,4 +1,5 @@
import asyncio
+import builtins
import io
import logging
@@ -55,3 +56,20 @@ async def test_styling(monkeypatch) -> None:
assert "\x1b[33mhello\x1b[0m" in f.getvalue()
t.done()
+
+
+async def test_cannot_print(monkeypatch) -> None:
+ def _raise(*args, **kwargs):
+ raise OSError
+
+ monkeypatch.setattr(builtins, "print", _raise)
+
+ t = termlog.TermLog()
+ with taddons.context(t) as tctx:
+ tctx.configure(t)
+ with pytest.raises(SystemExit) as exc_info:
+ logging.info("Should not log this, but raise instead")
+
+ assert exc_info.value.args[0] == 1
+
+ t.done()
| mitmdump jumps to 100% CPU when parent process exits
#### Problem Description
It took me two days to make this reproduce in isolation. I hope someone with Python skills can figure out what is happening here. Depending on what the root cause is this might not even be related to my funny architecture.
I'm spawning `mitmdump` from Node.js. If the node process exits mitmdump will be re-assigned to become a child of `systemd` (some unix wizardry). It will then immediately jump to 100% CPU and stay there. This _only_ happens when an addon is using at least one network event (go figure...). E.g. I'm using `client_connected` (works with `clientconnect` on v6 as well). If the addon is only using sth. like `running` the bug does not occur. Even better: if the addon originally only has "running" nothing bad happens. But if I then add a `client_connected` and save the file (and the addon is automatically reloaded) it will instantly jump to 100% CPU.
My guess is that it might be related to stdout and the switcheroo with the parent process? In my actual architecture the mitmdump process will poll the parent via gRPC every second and shutdown if it's gone. But the 100% CPU prevents that.
Update: while trying to write down the exact steps it turns out this might only reproduce via local venv and and not if you download the binary. I'm not sure, it's confusing. I'm confused. But I have video proof, so I'm not completely insane.
#### Steps to reproduce the behavior:
index.js
```js
const path = require('path');
const { spawn } = require('child_process');
function handleStdOut(data) {
console.log(`mitmdump stdout: ${data}`);
}
function handleStdError(data) {
console.error(`mitmdump stderr: ${data}`);
}
function handleExit(code) {
console.log(`mitm process exited with code ${code}`);
}
const mitm = spawn(
// Adjust this path
'/home/alex/Projects/Bandsalat/src/forks/mitmproxy/venv/bin/mitmdump',
['--quiet', '--set', 'connection_strategy=lazy', '--scripts', 'addon.py'],
{
detached: true,
windowsHide: true,
env: {
PYTHONUNBUFFERED: '1',
},
}
);
console.log(mitm.spawnargs);
mitm.unref();
mitm.on('exit', handleExit);
mitm.stdout.on('data', handleStdOut);
mitm.stderr.on('data', handleStdError);
```
addon.py
```py
class MyAddon:
def running(self):
print('running')
def client_connected(self, client):
print('client_connected')
addons = [
MyAddon()
]
```
1. I'm on Ubuntu
2. Adjust index.js to point to your local mitmproxy git venv
3. Launch `node index.js` (Node 14 or 16 work both for me)
4. Now open Chromium with mitmproxy configured. You don't need to enter any URL, Chromium will phone home anyway.
5. Keep Chromium open and ctrl+c the node process
6. Observe your fan getting louder and `top` showing mitmdump at 100% CPU
https://user-images.githubusercontent.com/679144/124594746-740a7080-de60-11eb-9ffb-a5fc4b3ba24a.mp4
#### System Information
Happens with both v6 and HEAD.
```
Mitmproxy: 7.0.0.dev (+492, commit af27556)
Python: 3.8.10
OpenSSL: OpenSSL 1.1.1i 8 Dec 2020
Platform: Linux-5.8.0-59-generic-x86_64-with-glibc2.29
```
| Current working theory: the addon `print` raises a broken pipe and the mitmdump error handling wants to log that broken pipe error to stderr, causing another broken pipe. And this somehow causes an infinite recursion of trying to write to stderr? Maybe this is just a matter of `if e.errno != errno.EPIPE:` in the right spot?
Fundamentally this is my problem and not a bug in mitmdump.
> Fundamentally this is my problem and not a bug in mitmdump.
I've changed my mind :smile: . While the bug only surfaces in the way I use mitmdump, I cannot fix this on my end. When the parent process unexpectedly closes (without cleaning up, i.e. killing the mitmdump child), Unix will re-parent mitmdump to the next parent. But this breaks the stdin/stdout pipes I had. This will also cause the GRPC service to go away (which the parent was running). That means the next time my addon tries to call the service it will crash (yes, I _could_ catch that). And then it tries to write to stderr, but it can't, it's gone. And I _think_ it will try so over and over and over. Which will then cause mitmdump to run at 100% CPU.
Does my explanation make sense? I've seen my mitmdump at 100% CPU (with an exited parent) multiple times in the past days and I'd love to fix it.
Where would be the right place to check for `if e.errno != errno.EPIPE:`? Does that sound like a good fix? Exiting the process when we can't write to stderr? I think everyone running mitmdump as a child process would benefit from that.
I've traced it down to
https://github.com/mitmproxy/mitmproxy/blob/f85c64401b0a9d1f60f85eaaf810fef1c46c4e08/mitmproxy/addonmanager.py#L50-L54
plus
https://github.com/mitmproxy/mitmproxy/blob/f85c64401b0a9d1f60f85eaaf810fef1c46c4e08/mitmproxy/log.py#L70-L74
If I add this before the ctx.log.error call
```py
file1 = open('/tmp/mitm/e.txt', 'a')
file1.write("Addon error: %s" % "".join(
traceback.format_exception(etype, value, tb)
))
file1.close()
```
I get an endless growing `e.txt` with
```
Addon error: Traceback (most recent call last):
File "addon.py", line 6, in client_connected
print('client_connected')
BrokenPipeError: [Errno 32] Broken pipe
Addon error: Traceback (most recent call last):
File "addon.py", line 6, in client_connected
print('client_connected')
BrokenPipeError: [Errno 32] Broken pipe
Addon error: Traceback (most recent call last):
File "addon.py", line 6, in client_connected
print('client_connected')
BrokenPipeError: [Errno 32] Broken pipe
Addon error: Traceback (most recent call last):
File "addon.py", line 6, in client_connected
print('client_connected')
BrokenPipeError: [Errno 32] Broken pipe
Addon error: Traceback (most recent call last):
File "/home/alex/Projects/mitmproxy/mitmproxy/addons/termlog.py", line 22, in add_log
click.secho(
File "/home/alex/Projects/mitmproxy/venv/lib/python3.8/site-packages/click/termui.py", line 659, in secho
return echo(message, file=file, nl=nl, err=err, color=color)
File "/home/alex/Projects/mitmproxy/venv/lib/python3.8/site-packages/click/utils.py", line 298, in echo
file.write(out) # type: ignore
BrokenPipeError: [Errno 32] Broken pipe
Addon error: Traceback (most recent call last):
File "/home/alex/Projects/mitmproxy/mitmproxy/addons/termlog.py", line 22, in add_log
click.secho(
File "/home/alex/Projects/mitmproxy/venv/lib/python3.8/site-packages/click/termui.py", line 659, in secho
return echo(message, file=file, nl=nl, err=err, color=color)
File "/home/alex/Projects/mitmproxy/venv/lib/python3.8/site-packages/click/utils.py", line 298, in echo
file.write(out) # type: ignore
BrokenPipeError: [Errno 32] Broken pipe
Addon error: Traceback (most recent call last):
File "/home/alex/Projects/mitmproxy/mitmproxy/addons/termlog.py", line 22, in add_log
click.secho(
File "/home/alex/Projects/mitmproxy/venv/lib/python3.8/site-packages/click/termui.py", line 659, in secho
return echo(message, file=file, nl=nl, err=err, color=color)
File "/home/alex/Projects/mitmproxy/venv/lib/python3.8/site-packages/click/utils.py", line 298, in echo
file.write(out) # type: ignore
BrokenPipeError: [Errno 32] Broken pipe
```
So this 100% confirms that when the parent process is gone, any error that the addon causes will cause an endless loop. The repro uses a simple `print` which itself will fail with EPIPE, but any error in the addon works. Because mitmproxy will try to write to a broken stderr.
Now the question is what is the proper fix? Ignoring all `EPIPE` doesn't sound like a good idea, because you might have other pipes that break in your addon. I don't know how the scheduling of the whole logging thing works, can't we wrap the final print in a `try`?
Edit: nvm, just a `try` is not enough. If logging the error fails the process needs to go down.
Thanks for looking into this! I think `TermLog.add_log` should just catch any OSErrors and then `sys.exit()` with a distinguishable exit code. As with streaming flows to disk, if we cannot write logfiles anymore we want to go down hard. | 2022-10-30T17:56:58 |
mitmproxy/mitmproxy | 5,701 | mitmproxy__mitmproxy-5701 | [
"5699"
] | 27cf2d2d1244f4f4b773fe619d15f5cb3b2e4b4c | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -108,7 +108,7 @@
"hypothesis>=5.8,<7",
"parver>=0.1,<2.0",
"pdoc>=4.0.0",
- "pyinstaller==5.6.1",
+ "pyinstaller==5.5",
"pytest-asyncio>=0.17,<0.21",
"pytest-cov>=2.7.1,<4.1",
"pytest-timeout>=1.3.3,<2.2",
| Latest release broken on Ubuntu 22.04 - ImportError: libffi.so.7: cannot open shared object file: No such file or directory
#### Problem Description
https://askubuntu.com/questions/1286772/libffi-so-7-cannot-open-shared-object-file-no-such-file-or-directory
I don't think our users should do anything with their system to make the binary run, correct?
```
$ ./mitmdump
Traceback (most recent call last):
File "mitmdump", line 3, in <module>
File "mitmproxy/tools/main.py", line 131, in mitmdump
File "PyInstaller/loader/pyimod02_importers.py", line 499, in exec_module
File "mitmproxy/tools/dump.py", line 1, in <module>
File "PyInstaller/loader/pyimod02_importers.py", line 499, in exec_module
File "mitmproxy/addons/__init__.py", line 10, in <module>
File "PyInstaller/loader/pyimod02_importers.py", line 499, in exec_module
File "mitmproxy/addons/cut.py", line 14, in <module>
File "PyInstaller/loader/pyimod02_importers.py", line 499, in exec_module
File "pyperclip/__init__.py", line 52, in <module>
File "PyInstaller/loader/pyimod02_importers.py", line 499, in exec_module
File "ctypes/__init__.py", line 8, in <module>
ImportError: libffi.so.7: cannot open shared object file: No such file or directory
[50935] Failed to execute script 'mitmdump' due to unhandled exception!
```
#### Steps to reproduce the behavior:
1. `mitmdump`
Repros in a clean `docker run --rm -it ubuntu:22.04` as well
#### System Information
9.0.0 just downloaded (I cannot run `mitmdump --version` as it doesn't launch)
| Huh, thanks for raising this. The compiled binary _does_ include `libffi.so.7.1.0`, so I'm not sure what exactly is broken here.
pyinstaller 5.1 with Python 3.10 works. Let's see who's at fault here. | 2022-10-31T16:29:01 |
|
mitmproxy/mitmproxy | 5,722 | mitmproxy__mitmproxy-5722 | [
"5706"
] | cf27d0af732301b0f3c6f003025654f72eba8945 | diff --git a/mitmproxy/options.py b/mitmproxy/options.py
--- a/mitmproxy/options.py
+++ b/mitmproxy/options.py
@@ -103,8 +103,9 @@ def __init__(self, **kwargs) -> None:
The proxy server type(s) to spawn. Can be passed multiple times.
Mitmproxy supports "regular" (HTTP), "transparent", "socks5", "reverse:SPEC",
- and "upstream:SPEC" proxy servers. For reverse and upstream proxy modes, SPEC
- is host specification in the form of "http[s]://host[:port]".
+ "upstream:SPEC", and "wireguard[:PATH]" proxy servers. For reverse and upstream proxy modes, SPEC
+ is host specification in the form of "http[s]://host[:port]". For WireGuard mode, PATH may point to
+ a file containing key material. If no such file exists, it will be created on startup.
You may append `@listen_port` or `@listen_host:listen_port` to override `listen_host` or `listen_port` for
a specific proxy mode. Features such as client playback will use the first mode to determine
diff --git a/mitmproxy/proxy/mode_servers.py b/mitmproxy/proxy/mode_servers.py
--- a/mitmproxy/proxy/mode_servers.py
+++ b/mitmproxy/proxy/mode_servers.py
@@ -308,6 +308,7 @@ async def start(self) -> None:
try:
if not conf_path.exists():
+ conf_path.parent.mkdir(parents=True, exist_ok=True)
conf_path.write_text(json.dumps({
"server_key": wg.genkey(),
"client_key": wg.genkey(),
| WireGuard missing in `--help` and `--options`
#### Problem Description
Maybe it's just my tired brain?
#### Steps to reproduce the behavior:
```
$: mitmdump --help
--mode MODE, -m MODE The proxy server type(s) to spawn. Can be passed multiple times. Mitmproxy supports "regular" (HTTP), "transparent", "socks5", "reverse:SPEC", and "upstream:SPEC" proxy servers. For reverse
and upstream proxy modes, SPEC is host specification in the form of "http[s]://host[:port]". You may append `@listen_port` or `@listen_host:listen_port` to override `listen_host` or
`listen_port` for a specific proxy mode. Features such as client playback will use the first mode to determine which upstream server to use. May be passed multiple times.
```
```
$: mitmdump --options
# The proxy server type(s) to spawn. Can be passed multiple times.
# Mitmproxy supports "regular" (HTTP), "transparent", "socks5",
# "reverse:SPEC", and "upstream:SPEC" proxy servers. For reverse and
# upstream proxy modes, SPEC is host specification in the form of
# "http[s]://host[:port]". You may append `@listen_port` or
# `@listen_host:listen_port` to override `listen_host` or `listen_port`
# for a specific proxy mode. Features such as client playback will use
# the first mode to determine which upstream server to use. Type
# sequence of str.
mode:
- regular
```
#### System Information
```
Mitmproxy: 10.0.0.dev binary
Python: 3.11.0
OpenSSL: OpenSSL 3.0.5 5 Jul 2022
Platform: Linux-5.15.0-52-generic-x86_64-with-glibc2.35
```
| 2022-11-03T22:18:21 |
||
mitmproxy/mitmproxy | 5,879 | mitmproxy__mitmproxy-5879 | [
"5878"
] | 3cdb8efc5e25a60334c27dc52695c6b9306d0e91 | diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -75,10 +75,10 @@
# It is not considered best practice to use install_requires to pin dependencies to specific versions.
install_requires=[
"aioquic_mitmproxy>=0.9.20,<0.10",
- "asgiref>=3.2.10,<3.6",
+ "asgiref>=3.2.10,<3.7",
"Brotli>=1.0,<1.1",
"certifi>=2019.9.11", # no semver here - this should always be on the last release!
- "cryptography>=38.0,<38.1",
+ "cryptography>=38.0,<39.1",
"flask>=1.1.1,<2.3",
"h11>=0.11,<0.15",
"h2>=4.1,<5",
@@ -89,7 +89,7 @@
"msgpack>=1.0.0, <1.1.0",
"passlib>=1.6.5, <1.8",
"protobuf>=3.14,<5",
- "pyOpenSSL>=22.1,<22.2",
+ "pyOpenSSL>=22.1,<23.1",
"pyparsing>=2.4.2,<3.1",
"pyperclip>=1.6.0,<1.9",
"ruamel.yaml>=0.16,<0.18",
@@ -110,14 +110,14 @@
"hypothesis>=5.8,<7",
"parver>=0.1,<2.0",
"pdoc>=4.0.0",
- "pyinstaller==5.6.2",
+ "pyinstaller==5.7.0",
"pytest-asyncio>=0.17,<0.21",
"pytest-cov>=2.7.1,<4.1",
"pytest-timeout>=1.3.3,<2.2",
- "pytest-xdist>=2.1.0,<3.1",
+ "pytest-xdist>=2.1.0,<3.2",
"pytest>=6.1.0,<8",
"requests>=2.9.1,<3",
- "tox>=3.5,<4",
+ "tox>=3.5,<5",
"wheel>=0.36.2,<0.39",
],
},
| Adopt Dependabot
I've only just learned that requires.io has been shut down. A big thank you to @omansion and @atabary for providing such a fantastic service over the years! ❤️
For mitmproxy this probably means we should migrate to Dependabot. This will probably mean a whole lot more PRs, let's see.
| 2023-01-15T22:24:34 |
||
mitmproxy/mitmproxy | 5,894 | mitmproxy__mitmproxy-5894 | [
"5470"
] | 0c4549f4cce06c217f62ee79a3d32fa8b5bbaaed | diff --git a/mitmproxy/contentviews/raw.py b/mitmproxy/contentviews/raw.py
--- a/mitmproxy/contentviews/raw.py
+++ b/mitmproxy/contentviews/raw.py
@@ -1,12 +1,11 @@
from . import base
-from mitmproxy.utils import strutils
class ViewRaw(base.View):
name = "Raw"
def __call__(self, data, **metadata):
- return "Raw", base.format_text(strutils.bytes_to_escaped_str(data, True))
+ return "Raw", base.format_text(data)
def render_priority(self, data: bytes, **metadata) -> float:
return 0.1 * float(bool(data))
| diff --git a/test/mitmproxy/contentviews/test_raw.py b/test/mitmproxy/contentviews/test_raw.py
--- a/test/mitmproxy/contentviews/test_raw.py
+++ b/test/mitmproxy/contentviews/test_raw.py
@@ -5,6 +5,16 @@
def test_view_raw():
v = full_eval(raw.ViewRaw())
assert v(b"foo")
+ # unicode
+ assert v("🫠".encode()) == (
+ "Raw",
+ [[("text", "🫠".encode())]],
+ )
+ # invalid utf8
+ assert v(b"\xFF") == (
+ "Raw",
+ [[("text", b"\xFF")]],
+ )
def test_render_priority():
| "raw" view is not raw, adds extra backslash
#### Problem Description
I just noticed during https://github.com/mitmproxy/mitmproxy/issues/5469#issuecomment-1191343747
#### Steps to reproduce the behavior:
http.txt
```
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 1
\
```
1. `ncat -l 1337 < http.txt`
2. `mitmproxy`
3. `curl --proxy localhost:8080 http://127.0.0.1:1337`
raw is `\\`:

hex:

#### System Information
```
Mitmproxy: 8.1.1 binary
Python: 3.10.5
OpenSSL: OpenSSL 3.0.3 3 May 2022
Platform: Linux-5.15.0-41-generic-x86_64-with-glibc2.35
```
| Raw mode currently escapes unprintable characters as well as backslashes so that the representation is unambiguous. I do agree though that the example you are showing is all but optimal, maybe we should just switch to rendering unprintable characters as �.
> maybe we should just switch to rendering unprintable characters as �.
That sounds reasonable to me. Text bodies would then be rendered 100% correctly (which I think is very important) and binary bodies would contain � as one would kind of expect (I don't think a lot of people would inspect binary bodies for anything other than text they contain [we could additionally also add a `strings(1)` view :thinking: ]) | 2023-01-28T15:10:36 |
mitmproxy/mitmproxy | 5,908 | mitmproxy__mitmproxy-5908 | [
"5907"
] | a7e50c793e9c6840d9f0fc162893e293477a358e | diff --git a/mitmproxy/http.py b/mitmproxy/http.py
--- a/mitmproxy/http.py
+++ b/mitmproxy/http.py
@@ -749,13 +749,7 @@ def host(self) -> str:
@host.setter
def host(self, val: Union[str, bytes]) -> None:
self.data.host = always_str(val, "idna", "strict")
-
- # Update host header
- if "Host" in self.data.headers:
- self.data.headers["Host"] = val
- # Update authority
- if self.data.authority:
- self.authority = url.hostport(self.scheme, self.host, self.port)
+ self._update_host_and_authority()
@property
def host_header(self) -> Optional[str]:
@@ -794,7 +788,21 @@ def port(self) -> int:
@port.setter
def port(self, port: int) -> None:
+ if not isinstance(port, int):
+ raise ValueError(f"Port must be an integer, not {port!r}.")
+
self.data.port = port
+ self._update_host_and_authority()
+
+ def _update_host_and_authority(self) -> None:
+ val = url.hostport(self.scheme, self.host, self.port)
+
+ # Update host header
+ if "Host" in self.data.headers:
+ self.data.headers["Host"] = val
+ # Update authority
+ if self.data.authority:
+ self.authority = val
@property
def path(self) -> str:
| diff --git a/test/mitmproxy/addons/test_mapremote.py b/test/mitmproxy/addons/test_mapremote.py
--- a/test/mitmproxy/addons/test_mapremote.py
+++ b/test/mitmproxy/addons/test_mapremote.py
@@ -27,6 +27,16 @@ def test_simple(self):
mr.request(f)
assert f.request.url == "https://mitmproxy.org/img/test.jpg"
+ def test_host_header(self):
+ mr = mapremote.MapRemote()
+ with taddons.context(mr) as tctx:
+ tctx.configure(mr, map_remote=["|http://[^/]+|http://example.com:4444"])
+ f = tflow.tflow()
+ f.request.url = b"http://example.org/example"
+ f.request.headers["Host"] = "example.org"
+ mr.request(f)
+ assert f.request.headers.get("Host", "") == "example.com:4444"
+
def test_is_killed(self):
mr = mapremote.MapRemote()
with taddons.context(mr) as tctx:
diff --git a/test/mitmproxy/test_http.py b/test/mitmproxy/test_http.py
--- a/test/mitmproxy/test_http.py
+++ b/test/mitmproxy/test_http.py
@@ -2,6 +2,7 @@
import email
import json
import time
+from typing import Any
from unittest import mock
import pytest
@@ -10,6 +11,7 @@
from mitmproxy import flowfilter
from mitmproxy.http import Headers
from mitmproxy.http import HTTPFlow
+from mitmproxy.http import Message
from mitmproxy.http import Request
from mitmproxy.http import Response
from mitmproxy.net.http.cookies import CookieAttrs
@@ -158,7 +160,9 @@ def test_scheme(self):
_test_decoded_attr(treq(), "scheme")
def test_port(self):
- _test_passthrough_attr(treq(), "port")
+ _test_passthrough_attr(treq(), "port", 1234)
+ with pytest.raises(ValueError):
+ treq().port = "foo"
def test_path(self):
_test_decoded_attr(treq(), "path")
@@ -199,8 +203,7 @@ def test_host_update_also_updates_header(self):
request.headers["Host"] = "foo"
request.authority = "foo"
request.host = "example.org"
- assert request.headers["Host"] == "example.org"
- assert request.authority == "example.org:22"
+ assert request.headers["Host"] == request.authority == "example.org:22"
def test_get_host_header(self):
no_hdr = treq()
@@ -864,10 +867,10 @@ def test_items(self):
]
-def _test_passthrough_attr(message, attr):
+def _test_passthrough_attr(message: Message, attr: str, value: Any = b"foo") -> None:
assert getattr(message, attr) == getattr(message.data, attr)
- setattr(message, attr, b"foo")
- assert getattr(message.data, attr) == b"foo"
+ setattr(message, attr, value)
+ assert getattr(message.data, attr) == value
def _test_decoded_attr(message, attr):
| Map remote should include port in Host header (mitmweb)
#### Problem Description
When using `--map-remote` in `mitmweb`, the request URL gets replaced, and the `Host` gets updated. However, the port is not added to the Host header, leading to problems when using non-standard ports.
#### Steps to reproduce the behavior:
1. `mitmweb --map-remote '|http://[^/]+|http://portquiz.net:4444' --listen-port 9090'`
2. `curl --proxy http://127.0.0.1:9090 http://github.com`
3. Host header does not contain port
4. It should: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host
#### System Information
```
Mitmproxy: 9.0.1
Python: 3.11.1
OpenSSL: OpenSSL 1.1.1s 1 Nov 2022
Platform: macOS-13.2-arm64-arm-64bit
``
| The map remote addon just sets a new URL [here](https://github.com/mitmproxy/mitmproxy/blob/dfeddcf4add66a6ebab1d508c47256185ef6ddb7/mitmproxy/addons/mapremote.py#L68), which seems like the right thing to do. Seems like the bug is in [`mitmproxy.http.Request.host` and `mitmproxy.http.Request.port`](https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/http.py) then, contributions welcome! | 2023-02-04T10:56:06 |
mitmproxy/mitmproxy | 5,923 | mitmproxy__mitmproxy-5923 | [
"5921"
] | 5969f25db4cbbc3edc91947205b89edca58f0818 | 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
@@ -255,21 +255,17 @@ def view_message_stream(self) -> urwid.Widget:
viewmode = self.master.commands.call("console.flowview.mode")
widget_lines = []
-
- from_client = flow.messages[0].from_client
for m in flow.messages:
_, lines, _ = contentviews.get_message_content_view(viewmode, m, flow)
for line in lines:
- if from_client:
+ if m.from_client:
line.insert(0, self.FROM_CLIENT_MARKER)
else:
line.insert(0, self.TO_CLIENT_MARKER)
widget_lines.append(urwid.Text(line))
- from_client = not from_client
-
if flow.intercepted:
markup = widget_lines[-1].get_text()[0]
widget_lines[-1].set_text(("intercept", markup))
| Wrong message direction indicator in console raw TCP view
#### Problem Description
In the flow view of the console tool, for raw TCP flows the `⇒` and `⇐` direction indicators (from client and to client) always alternate and don't represent the correct direction.
#### Steps to reproduce the behavior:
1. Start a TCP server: `ncat --listen localhost 2000`
2. Start mitmproxy: `mitmproxy --mode=reverse:tcp://localhost:2000@2001 --tcp-hosts='.*'`
3. Connect to the reverse proxy: `ncat localhost 2000`. Enter multiple lines, e.g. `a`, press enter, `b`, press enter.
4. In mitmproxy, open the flow view for the new flow. There the two messages have different direction indicators even though they were both sent by the client.
#### System Information
```
Mitmproxy: 9.0.1 binary
Python: 3.11.0
OpenSSL: OpenSSL 3.0.7 1 Nov 2022
Platform: Linux-6.1.9-arch1-2-x86_64-with-glibc2.37
```
#### Fix
The bug is in the function [`view_message_stream`](https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/tools/console/flowview.py#L248) and was introduced in https://github.com/mitmproxy/mitmproxy/pull/3970/commits/fe75f14ea29d0654c3a688ecc4c3669a946ea2a8. The solution could be the same as in the similar function [`view_websocket_messages`](https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/tools/console/flowview.py#L197).
I would like to contribute a fix for this issue.
| Thanks for the clear description. And yes please, a fix would be very welcome! 😃 | 2023-02-09T19:05:44 |
|
mitmproxy/mitmproxy | 6,020 | mitmproxy__mitmproxy-6020 | [
"5935"
] | 84b03c06e3d857c70daa2eb0d0c83a0c1af556ba | diff --git a/mitmproxy/addons/errorcheck.py b/mitmproxy/addons/errorcheck.py
--- a/mitmproxy/addons/errorcheck.py
+++ b/mitmproxy/addons/errorcheck.py
@@ -8,8 +8,14 @@
class ErrorCheck:
"""Monitor startup for error log entries, and terminate immediately if there are some."""
- def __init__(self, log_to_stderr: bool = False) -> None:
- self.log_to_stderr = log_to_stderr
+ repeat_errors_on_stderr: bool
+ """
+ Repeat all errors on stderr before exiting.
+ This is useful for the console UI, which otherwise swallows all output.
+ """
+
+ def __init__(self, repeat_errors_on_stderr: bool = False) -> None:
+ self.repeat_errors_on_stderr = repeat_errors_on_stderr
self.logger = ErrorCheckHandler()
self.logger.install()
@@ -21,10 +27,14 @@ async def shutdown_if_errored(self):
# don't run immediately, wait for all logging tasks to finish.
await asyncio.sleep(0)
if self.logger.has_errored:
- if self.log_to_stderr:
- plural = "s" if len(self.logger.has_errored) > 1 else ""
+ plural = "s" if len(self.logger.has_errored) > 1 else ""
+ if self.repeat_errors_on_stderr:
msg = "\n".join(r.msg for r in self.logger.has_errored)
- print(f"Error{plural} on startup: {msg}", file=sys.stderr)
+ print(f"Error{plural} logged during startup: {msg}", file=sys.stderr)
+ else:
+ print(
+ f"Error{plural} logged during startup, exiting...", file=sys.stderr
+ )
sys.exit(1)
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
@@ -55,7 +55,7 @@ def __init__(self, opts: options.Options) -> None:
readfile.ReadFile(),
consoleaddons.ConsoleAddon(self),
keymap.KeymapConfig(self),
- errorcheck.ErrorCheck(log_to_stderr=True),
+ errorcheck.ErrorCheck(repeat_errors_on_stderr=True),
)
self.window: window.Window | None = None
| diff --git a/test/mitmproxy/addons/test_errorcheck.py b/test/mitmproxy/addons/test_errorcheck.py
--- a/test/mitmproxy/addons/test_errorcheck.py
+++ b/test/mitmproxy/addons/test_errorcheck.py
@@ -1,3 +1,5 @@
+import logging
+
import pytest
from mitmproxy.addons.errorcheck import ErrorCheck
@@ -13,10 +15,19 @@ def test_errorcheck(tdata, capsys):
tdata.path("mitmproxy/data/addonscripts/load_error.py"),
]
)
- assert "Error on startup" in capsys.readouterr().err
+ assert "Error logged during startup" in capsys.readouterr().err
async def test_no_error():
e = ErrorCheck()
await e.shutdown_if_errored()
e.finish()
+
+
+async def test_error_message(capsys):
+ e = ErrorCheck()
+ logging.error("wat")
+ logging.error("wat")
+ with pytest.raises(SystemExit):
+ await e.shutdown_if_errored()
+ assert "Errors logged during startup" in capsys.readouterr().err
| Logging verbosity impacts logs from a script
#### Problem Description
When I set the log verbosity in the config file to `warn`, i.e.
```
console_eventlog_verbosity: warn
termlog_verbosity: warn
```
logs that I'm writing in a script at that log level or higher are not outputted to stdout, whereas they are if I leave the verbosity at `info`, they are.
#### Steps to reproduce the behavior:
1. Set the `eventlog` and `termlog` verbosity to `warn`
2. Run a script with something like the following:
```python
import logging
class Handler
def __init__(self):
logging.basicConfig(level=logging.WARNING,
format='%(asctime)s %(levelname)s %(name)s %(message)s',
filename="/var/log/mitmproxy.log"
)
self.logger = logging.getLogger(__name__)
def request(self, flow: http.HTTPFlow):
self.logger.warning("A warning here")
```
#### System Information
Mitmproxy: 9.0.1
Python: 3.10.10
OpenSSL: OpenSSL 3.0.7 1 Nov 2022
Platform: Linux-5.10.162-141.675.amzn2.x86_64-x86_64-with
| I can't reproduce this with what you provided. The following works as expected for me:
```python
import logging
from mitmproxy import http
class Handler:
def __init__(self):
logging.basicConfig(level=logging.WARNING,
format='%(asctime)s %(levelname)s %(name)s %(message)s',
filename="/var/log/mitmproxy.log"
)
self.logger = logging.getLogger(__name__)
def request(self, flow: http.HTTPFlow):
self.logger.warning("A warning here")
addons = [Handler()]
```
```shell
mitmdump -s foo.py --set termlog_verbosity=warn
```
```shell
curl -x localhost:8080 -k https://example.com
```

<hr>
Mitmproxy: 10.0.0.dev (+217, commit 2663b42)
Python: 3.11.2
OpenSSL: OpenSSL 3.0.8 7 Feb 2023
Platform: Linux-4.4.0-22621-Microsoft-x86_64-with-glibc2.35
Sorry, I think my problem was stemming from a different behavior. If I call `self.logger.error("My error")`, it terminates the mitmproxy process. Is this intended, any logged error stops the process?
Absolutely not, except during startup. Again this needs a full repro. :)
```
#!/usr/bin/env python3
from mitmproxy import http
from mitmproxy import coretypes
import logging
class Throttling:
def __init__(self):
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(name)s %(message)s',
filename = "/var/log/mitmprox/mitmproxy.log",
filemode= "a"
)
self.logger = logging.getLogger(__name__)
self.logger.error("Init called")
def request(self, flow: http.HTTPFlow):
self.logger.warning("received request")
addons = [Throttling()]
```
Logging an error during ``__init__`` terminates the container I'm running this in.
Yes, errors during startup are intentionally fatal. The idea here is that those likely point to mistakes in the invocation, and it would be worse to silently swallow those.
The relevant addon is here: https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/addons/errorcheck.py I'd be open to making this configurable, but it seems like it would be a reasonable alternative to just `.warn` in your case?
Using `.warn` is acceptable, just wasn't expecting logging an error during init to be fatal.
If you have ideas how how we can improve the dev experience here I'm all ears. Would an explicit message on stdout help? I'm thinking of something like "Errors logged during startup, exiting...".
An explicit message would definitely help, or even just a note in the documentation to expect this behavior, both would be ok for me. | 2023-03-26T18:06:12 |
mitmproxy/mitmproxy | 6,032 | mitmproxy__mitmproxy-6032 | [
"6029"
] | 87577578925d28b6f1c8f00ffb6b283bfa80c993 | diff --git a/mitmproxy/command.py b/mitmproxy/command.py
--- a/mitmproxy/command.py
+++ b/mitmproxy/command.py
@@ -22,7 +22,7 @@
def verify_arg_signature(f: Callable, args: Iterable[Any], kwargs: dict) -> None:
- sig = inspect.signature(f)
+ sig = inspect.signature(f, eval_str=True)
try:
sig.bind(*args, **kwargs)
except TypeError as v:
@@ -71,7 +71,7 @@ def __init__(self, manager: "CommandManager", name: str, func: Callable) -> None
self.name = name
self.manager = manager
self.func = func
- self.signature = inspect.signature(self.func)
+ self.signature = inspect.signature(self.func, eval_str=True)
if func.__doc__:
txt = func.__doc__.strip()
| Broken command argument type parsing
#### Problem Description
It seems like our command argument type parsing does not like `from __future__ import annotations`.
#### Steps to reproduce the behavior:
1. `mitmproxy`
2. `[n] [enter] [r]`
| 2023-03-29T09:09:31 |
||
mitmproxy/mitmproxy | 6,087 | mitmproxy__mitmproxy-6087 | [
"6085"
] | 33682c206ef1568a44de342bc5e9ec998762becf | 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
@@ -17,6 +17,7 @@ def map(km: Keymap) -> None:
km.add("E", "console.view.eventlog", ["commonkey", "global"], "View event log")
km.add("Q", "console.exit", ["global"], "Exit immediately")
km.add("q", "console.view.pop", ["commonkey", "global"], "Exit the current view")
+ km.add("esc", "console.view.pop", ["commonkey", "global"], "Exit the current view")
km.add("-", "console.layout.cycle", ["global"], "Cycle to next layout")
km.add("ctrl right", "console.panes.next", ["global"], "Focus next layout pane")
km.add("ctrl left", "console.panes.prev", ["global"], "Focus previous layout pane")
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
@@ -1,5 +1,6 @@
import logging
import os
+from collections import defaultdict
from collections.abc import Sequence
from functools import cache
@@ -71,9 +72,7 @@ def sortkey(self):
class Keymap:
def __init__(self, master):
self.executor = commandexecutor.CommandExecutor(master)
- self.keys: dict[str, dict[str, Binding]] = {}
- for c in Contexts:
- self.keys[c] = {}
+ self.keys: dict[str, dict[str, Binding]] = defaultdict(dict)
self.bindings = []
def _check_contexts(self, contexts):
| UI: Navigation: Additionally allow Esc-key to navigate back.
#### Problem Description
First time using mitmproxy instead of mitmweb:
I intuitively tried navigating back to the flow list (initial view) after entering the view of a single flow using <kbd>Esc</kbd>.
#### Proposal
Additionally to <kbd>q</kbd> allow to use <kbd>Esc</kbd> to navigate back.
| That's a good keybind suggestion. 👍 | 2023-04-27T10:04:17 |
|
mitmproxy/mitmproxy | 6,088 | mitmproxy__mitmproxy-6088 | [
"6086"
] | 2261346334d91029db80922c0432feff0b094b40 | 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
@@ -82,7 +82,12 @@ def map(km: Keymap) -> None:
"Export this flow to file",
)
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(
+ "F",
+ "set console_focus_follow toggle",
+ ["flowlist", "flowview"],
+ "Set focus follow",
+ )
km.add(
"ctrl l",
"console.command cut.clip ",
| Toggling follow new option fails in single flow view.
#### Problem Description
Toggling follow new flow option via <kbd>F</kbd> does not work while in the view of a single flow.
#### Steps to reproduce the behavior:
1. launch mitmproxy
2. continually generate new requests
3. activate `Follow new` option
4. enter a flow
5. try to deactivate `Follow new` option
6. error: the view still follows the new flows
#### System Information
mitmproxy version 9.0.1
| Given that we don't use `F` for something else at the moment, I would be fine with also assigning it to `Follow new` in the individual flow view. PRs welcome! | 2023-04-27T11:43:27 |
|
mitmproxy/mitmproxy | 6,117 | mitmproxy__mitmproxy-6117 | [
"6115"
] | 018614503531b8a93afabae6d5b912be454c191c | diff --git a/examples/addons/http-reply-from-proxy.py b/examples/addons/http-reply-from-proxy.py
--- a/examples/addons/http-reply-from-proxy.py
+++ b/examples/addons/http-reply-from-proxy.py
@@ -1,4 +1,4 @@
-"""Send a reply from the proxy without sending any data to the remote server."""
+"""Send a reply from the proxy without sending the request to the remote server."""
from mitmproxy import http
| Warn new users about the lazy creation of connections (when requests are expected to be served in the script fully and only)
#### Problem Description
The [example script](https://docs.mitmproxy.org/stable/addons-examples/#http-reply-from-proxy) for not sending any data to the server does not prevent mitmproxy from **establishing a connection** to the server.
For which reason is said connection established when no data has to be sent to this host right away and possibly never in the future?
I trusted mitmproxy to **not send _any_ data, as stated**, but I had to discover (the hard way) that **that's not the case**.
I used mitmproxy in an environment where it required to stay silent, but it wasn't compliant.
Could you please consider warning new users about this behavior?
<strike>Is there an easy way to prevent establishing connections?
Is it planned to do so on default in this case?</strike>
*EDIT*: Trying to prevent connections by rerouting the connection to a closed port killed the flow for the client. Routing to a different host with invalid certificate worked though, warning me in the event log and suggesting setting connection strategy to lazy and it worked.
#### Steps to reproduce the behavior:
1. Load the example script
2. Have the client request examle.com
3. View the event log
#### System Information
Mitmproxy: 9.0.1
Python: 3.10.6
OpenSSL: OpenSSL 3.0.7 1 Nov 2022
Platform: Linux-5.15.0-71-generic-x86_64-with-glibc2.35
| You can use `--set connection_strategy=lazy` to prevent this behavior, see https://docs.mitmproxy.org/stable/concepts-options/#connection_strategy for more details
> Could you please consider warning new users about this behavior?
I think we could add a comment to the example script mentioning this? Not sure where else you would expect this warning. | 2023-05-08T19:19:27 |
|
mitmproxy/mitmproxy | 6,127 | mitmproxy__mitmproxy-6127 | [
"4272"
] | 90686abe822634c0faf1eae7d7927e67bd46013f | diff --git a/examples/addons/duplicate-modify-replay.py b/examples/addons/duplicate-modify-replay.py
--- a/examples/addons/duplicate-modify-replay.py
+++ b/examples/addons/duplicate-modify-replay.py
@@ -10,6 +10,6 @@ def request(flow):
# 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.flows.add", [flow])
+ ctx.master.commands.call("view.flows.duplicate", [flow])
flow.request.path = "/changed"
ctx.master.commands.call("replay.client", [flow])
| `view.flows.add` command does not exist but the examples reference it
#### Problem Description
The `view.flows.add` command does not exist but the example `duplicate-modify-replay.py` shows this command being used.
`replay.client` seems to perform both the "add to view" and "replay" function.
| 2023-05-14T07:20:55 |
||
mitmproxy/mitmproxy | 6,148 | mitmproxy__mitmproxy-6148 | [
"6143"
] | ab9429e3f6f831290f2a104a25b084f3f25b6452 | 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
@@ -1043,7 +1043,12 @@ def get_connection(
self.mode == HTTPMode.transparent
and event.address == self.context.server.address
):
- context.server.sni = self.context.client.sni or event.address[0]
+ # reverse proxy mode may set self.context.server.sni, which takes precedence.
+ context.server.sni = (
+ self.context.server.sni
+ or self.context.client.sni
+ or event.address[0]
+ )
else:
context.server.sni = event.address[0]
if context.server.transport_protocol == "tcp":
| diff --git a/test/mitmproxy/proxy/layers/http/test_http.py b/test/mitmproxy/proxy/layers/http/test_http.py
--- a/test/mitmproxy/proxy/layers/http/test_http.py
+++ b/test/mitmproxy/proxy/layers/http/test_http.py
@@ -1432,6 +1432,29 @@ def test_transparent_sni(tctx):
assert server().sni == "example.com"
+def test_reverse_sni(tctx):
+ """Test that we use the destination address as SNI in reverse mode."""
+ tctx.client.sni = "localhost"
+ tctx.server.address = ("192.0.2.42", 443)
+ tctx.server.tls = True
+ tctx.server.sni = "example.local"
+
+ flow = Placeholder(HTTPFlow)
+
+ server = Placeholder(Server)
+ assert (
+ Playbook(http.HttpLayer(tctx, HTTPMode.transparent))
+ >> DataReceived(tctx.client, b"GET / HTTP/1.1\r\n\r\n")
+ << http.HttpRequestHeadersHook(flow)
+ >> reply()
+ << http.HttpRequestHook(flow)
+ >> reply()
+ << OpenConnection(server)
+ )
+ assert server().address == ("192.0.2.42", 443)
+ assert server().sni == "example.local"
+
+
def test_original_server_disconnects(tctx):
"""Test that we correctly handle the case where the initial server conn is just closed."""
tctx.server.state = ConnectionState.OPEN
| Wrong SNI hostname used for reverse HTTPS proxy
#### Problem Description
When using mitmproxy in reverse proxy mode, it attempts to use the mitmproxy's domain for SNI in the outer TLS connection, fails to validate that connection and returns "502 Bad Gateway" -- "Certificate verify failed: Hostname mismatch"
#### Steps to reproduce the behavior:
1. Start mitmproxy in reverse proxy mode, e.g.
```mitmproxy --mode reverse:https://www.chimieparistech.psl.eu@8081 --certs locahost=localhost.pem```
3. Get https://localhost:8081/ with Chrome or Edge
mitmproxy logs...
```warn: [10:40:24.473][[::1]:62455] Server TLS handshake failed. Certificate verify failed: hostname mismatch```
... and returns to the browser ...
502 Bad Gateway, Certificate verify failed: hostname mismatch.
A packet capture of the traffic shows that mitmproxy sends at least 2 client Hello packets to the Chimieparistech server. In the first one the SNI is www.chimieparistech.psl.eu but right after, the second one has for SNI : localhost.
Problem does not repeat when using Firefox or curl.
#### System Information
Mitmproxy: 9.0.1
Python: 3.11.2
OpenSSL: OpenSSL 3.0.7 1 Nov 2022
Platform: Windows-10-10.0.22621-SP0
Chrome : Version 113.0.5672.127)
Edge : Version 113.0.1774.50)
| Can you reproduce this on the main branch?
Yes I can reproduce it on the main branch.
I forgot an important fact : problem happens only one out of two times. Page loads correctly in the browser, but when I reload it fails. Or I click on a link, it fails but when I reload it loads correctly.
Thank you.
Thanks, that was the missing bit! Here's a simplified reproducer:
```
$ mitmdump --mode reverse:https://www.chimieparistech.psl.eu@8081 --set proxy_debug -vvv
$ curl https://localhost:8081/robots.txt https://localhost:8081/robots.txt -kq --rate 6/m
```
The problem is in this snippet here - not sure yet what's the best way to fix it:
https://github.com/mitmproxy/mitmproxy/blob/ab9429e3f6f831290f2a104a25b084f3f25b6452/mitmproxy/proxy/layers/http/__init__.py#L1040-L1046 | 2023-05-28T16:28:44 |
mitmproxy/mitmproxy | 6,221 | mitmproxy__mitmproxy-6221 | [
"5891",
"6136"
] | fd01a0aa95b575ce9bf696fd9530f911bfd07fc5 | diff --git a/mitmproxy/proxy/mode_servers.py b/mitmproxy/proxy/mode_servers.py
--- a/mitmproxy/proxy/mode_servers.py
+++ b/mitmproxy/proxy/mode_servers.py
@@ -279,7 +279,7 @@ async def _start(self) -> None:
assert (
self.mode.custom_listen_host is None
) # since [@ [listen_addr:]listen_port]
- message += f"\nTry specifying a different port by using `--mode {self.mode.full_spec}@{port + 1}`."
+ message += f"\nTry specifying a different port by using `--mode {self.mode.full_spec}@{port + 2}`."
raise OSError(e.errno, message, e.filename) from e
async def _stop(self) -> None:
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
@@ -103,7 +103,7 @@ async def running(self):
except OSError as e:
message = f"Web server failed to listen on {self.options.web_host or '*'}:{self.options.web_port} with {e}"
if e.errno == errno.EADDRINUSE:
- message += f"\nTry specifying a different port by using `--set web_port={self.options.web_port + 1}`."
+ message += f"\nTry specifying a different port by using `--set web_port={self.options.web_port + 2}`."
raise OSError(e.errno, message, e.filename) from e
logger.info(
| diff --git a/test/mitmproxy/tools/web/test_master.py b/test/mitmproxy/tools/web/test_master.py
--- a/test/mitmproxy/tools/web/test_master.py
+++ b/test/mitmproxy/tools/web/test_master.py
@@ -15,6 +15,6 @@ async def test_reuse():
master = WebMaster(Options(), with_termlog=False)
master.options.web_host = "127.0.0.1"
master.options.web_port = port
- with pytest.raises(OSError, match=f"--set web_port={port + 1}"):
+ with pytest.raises(OSError, match=f"--set web_port={port + 2}"):
await master.running()
server.close()
| Misleading/incorrect message when port 8080 is taken (mitmweb)
#### Problem Description
- When port 8080 is already taken, `mitmweb` recommends you switch to port 8081.
- However, the web UI is already running on port 8081. The two collide, but no error message is printed.
- If you try to proxy your connections to 8081 as it's telling you, everything breaks.
- This is mainly a problem because non-experienced users won't know that the web UI runs on port 8081, and because no error is printed when the two collide, the proxy just doesn't work for no apparent reason.
#### Steps to reproduce the behavior:
1. Run any service on port 8080 (anything works as long as it blocks that port).
2. Run `mitmweb` (no arguments). A message is printed stating that port 8080 is taken and that you should switch to 8081 (!)
3. If you switch to port 8081, no errors are printed but a collision with the web UI happens silently. The web UI opens telling you to point your proxy to port 8081, which doesn't work.
#### System Information
```
Mitmproxy: 9.0.1
Python: 3.10.9
OpenSSL: OpenSSL 1.1.1s 1 Nov 2022
Platform: macOS-13.2-arm64-arm-64bit
```
Use dynamic port assignment to resolve collision issue between mitmweb and web UI
#### Description
To solve #5891, the fix introduces dynamic port assignment by specifying port 0. When mitmweb is started without specifying a port, it uses
```python
socket.bind(('', 0))
```
which allows the operating system to assign an available port.
#### Checklist
- [x] I have updated tests where applicable.
- [ ] I have added an entry to the CHANGELOG.
| This seems like an already fixed issue (I'm using Mitmproxy: 10.0.0.dev), I tried this:
```bash
mitmweb --listen-port 8081 # another service is blocking port 8080
```
and an error is raised:
```python
...
File "/path/to/mitmproxy/mitmproxy/tools/web/master.py", line 107, in running
raise OSError(e.errno, message, e.filename) from e
OSError: [Errno 98] Web server failed to listen on 127.0.0.1:8081 with [Errno 98] Address already in use
Try specifying a different port by using `--set web_port=8082`.
```
That's odd. This is what happens for me:
`mitmweb` (no port specifier)
```
Error on startup: [Errno 48] HTTP(S) proxy failed to listen on *:8080 with [Errno 48] error while attempting to bind on address ('0.0.0.0', 8080): address already in use
Try specifying a different port by using `--mode regular@8081`.
```
Then using the recommended flag, it starts fine even though there's the collision.
Which OSes are y'all on?
On Fri, Jan 27, 2023, 13:37 Isaac McFadyen ***@***.***> wrote:
> That's odd. This is what happens for me:
> mitmweb (no port specifier)
>
> Error on startup: [Errno 48] HTTP(S) proxy failed to listen on *:8080 with [Errno 48] error while attempting to bind on address ('0.0.0.0', 8080): address already in use
> Try specifying a different port by using `--mode ***@***.***`.
>
> Then using the recommended flag, it starts fine.
>
> —
> Reply to this email directly, view it on GitHub
> <https://github.com/mitmproxy/mitmproxy/issues/5891#issuecomment-1406447848>,
> or unsubscribe
> <https://github.com/notifications/unsubscribe-auth/AAHY2PWASNVSJQOHGTYB4PDWUO6P7ANCNFSM6AAAAAAUIBWKBU>
> .
> You are receiving this because you are subscribed to this thread.Message
> ID: ***@***.***>
>
I'm running on macOS Ventura 13.2 (ARM64, Apple Silicon)
I'm on Fedora 37
I tried this on macOS Big Sur:
```python
$ mitmweb # port 8080 is blocked
Web server listening at http://127.0.0.1:8081/
[Errno 48] error while attempting to bind on address ('0.0.0.0', 8080): address already in use
Task exception was never retrieved
future: <Task finished name='Task-4' coro=<ErrorCheck._shutdown_if_errored() done, defined at /path/to/mitmproxy/venv/lib/python3.8/site-packages/mitmproxy/addons/errorcheck.py:18> exception=SystemExit(1)>
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 603, in run_until_complete
self.run_forever()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
self._run_once()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
handle._run()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/events.py", line 81, in _run
self._context.run(self._callback, *self._args)
File "/path/to/mitmproxy/venv/lib/python3.8/site-packages/mitmproxy/addons/errorcheck.py", line 20, in _shutdown_if_errored
sys.exit(1)
SystemExit: 1
```
This does try to open the web page but I can't replicate rest of the behaviour.
Sorry I was testing an older version of mitmproxy, upgraded to mitmproxy 9.0.1 and this issue does exist.
This seemed like an issue in tornado, I am not yet exactly sure why this works but if I comment out the lines in tornado's `netutils.py` setting `socket.SO_REUSEADDR` then it works as expected on macOS too. These are the lines:
- [netutil.py#L135](https://github.com/tornadoweb/tornado/blob/59536016e37704a1c47a3a0d262f46ceb6132c06/tornado/netutil.py#L135)
- [netutil.py#L141](https://github.com/tornadoweb/tornado/blob/59536016e37704a1c47a3a0d262f46ceb6132c06/tornado/netutil.py#L141)
This could be due to the fact that the proxy binds to all local addresses whereas the web page only binds to 127.0.0.1 and through whatever magic SO_REUSEADDR does, this might be allowing the web page to bind to port 8081 even when the proxy is already bound to that port. Running the following command, it fixes the issue (assuming raising an error is the desired behaviour):
```
mitmweb --mode regular@8081 --web-host 0.0.0.0
```
| 2023-07-02T11:24:41 |
mitmproxy/mitmproxy | 6,305 | mitmproxy__mitmproxy-6305 | [
"6225"
] | ba9f74b248e06405bcbcf42f0733d60d4242f4ef | 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
@@ -375,7 +375,9 @@ def edit_focus_options(self) -> Sequence[str]:
flow = self.master.view.focus.flow
focus_options = []
- if isinstance(flow, tcp.TCPFlow):
+ if flow is None:
+ raise exceptions.CommandError("No flow selected.")
+ elif isinstance(flow, tcp.TCPFlow):
focus_options = ["tcp-message"]
elif isinstance(flow, udp.UDPFlow):
focus_options = ["udp-message"]
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
@@ -74,7 +74,7 @@ def map(km: Keymap) -> None:
"D", "view.flows.duplicate @focus", ["flowlist", "flowview"], "Duplicate flow"
)
km.add(
- "e",
+ "x",
"""
console.choose.cmd Format export.formats
console.command export.file {choice} @focus
@@ -156,7 +156,7 @@ def map(km: Keymap) -> None:
console.choose.cmd Part console.edit.focus.options
console.edit.focus {choice}
""",
- ["flowview"],
+ ["flowlist", "flowview"],
"Edit a flow component",
)
km.add(
diff --git a/mitmproxy/tools/console/quickhelp.py b/mitmproxy/tools/console/quickhelp.py
--- a/mitmproxy/tools/console/quickhelp.py
+++ b/mitmproxy/tools/console/quickhelp.py
@@ -73,6 +73,7 @@ def make(
top_items["Unmark"] = "Toggle mark on this flow"
else:
top_items["Mark"] = "Toggle mark on this flow"
+ top_items["Edit"] = "Edit a flow component"
if focused_flow.intercepted:
top_items["Resume"] = "Resume this intercepted flow"
if focused_flow.modified():
| Both Edit and Export share the same key binding
#### Problem Description
When in flow view, both `Edit` and `Export` commands are bound to the `e` key by default.
<img width="493" alt="imagen" src="https://github.com/mitmproxy/mitmproxy/assets/231822/362a928e-1634-4085-928a-b391b576fa37">
`Export` could use a different binding by default, like `x`.
#### System Information
Mitmproxy: 9.0.1
Python: 3.11.3
OpenSSL: OpenSSL 1.1.1u 30 May 2023
Platform: macOS-12.6.5-arm64-arm-64bit
| Thanks for catching this! Definitely something we want to fix. Maybe we move export to `x` in all contexts? Does anyone have any other ideas/proposals? | 2023-08-09T00:45:37 |
|
mitmproxy/mitmproxy | 6,373 | mitmproxy__mitmproxy-6373 | [
"4651",
"5609"
] | dd1ee72b21d689cfca31d02cfdfb66cb0226ae5e | 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
@@ -97,7 +97,9 @@ async def running(self):
tornado.ioloop.IOLoop.current()
# Add our web app.
- http_server = tornado.httpserver.HTTPServer(self.app)
+ http_server = tornado.httpserver.HTTPServer(
+ self.app, max_buffer_size=2**32
+ ) # 4GB
try:
http_server.listen(self.options.web_port, self.options.web_host)
except OSError as e:
| Outfile -w cannot be loaded
#### Problem Description
When the dump file is getting bigger, about 100mb it's not loaded anymore.
#### Steps to reproduce the behavior:
Make a big outfile and try to open it with an new instance of mitmweb.
#### System Information
Mitmweb Windows 10 6.0.2
mitmweb Not loading my saved flow
So I recorded some actions with mitmweb and saved the flow.
Then I closed mitmweb, and reopened it. Then I went to open the saved flow file (which is 100 megabytes). But when I open it, the requests and responses do not appear?
| This report is not actionable. Which browser are you using? Are there any error messages, either in your browser's developer tools or in mitmweb's console window?
In order to investigate this, we need more details. How can this be reproduced? Do you have a flow sample you can share? | 2023-09-19T05:11:49 |
|
mitmproxy/mitmproxy | 6,382 | mitmproxy__mitmproxy-6382 | [
"6381"
] | 95fe3f99298ce44a66828f939dddce54068f5d65 | diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py
--- a/mitmproxy/certs.py
+++ b/mitmproxy/certs.py
@@ -270,6 +270,7 @@ def dummy_cert(
try:
ip = ipaddress.ip_address(x)
except ValueError:
+ x = x.encode("idna").decode()
ss.append(x509.DNSName(x))
else:
ss.append(x509.IPAddress(ip))
| 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
@@ -141,11 +141,17 @@ def test_with_ca(self, tstore):
tstore.default_privatekey,
tstore.default_ca._cert,
"foo.com",
- ["one.com", "two.com", "*.three.com", "127.0.0.1"],
+ ["one.com", "two.com", "*.three.com", "127.0.0.1", "bücher.example"],
"Foo Ltd.",
)
assert r.cn == "foo.com"
- assert r.altnames == ["one.com", "two.com", "*.three.com", "127.0.0.1"]
+ assert r.altnames == [
+ "one.com",
+ "two.com",
+ "*.three.com",
+ "xn--bcher-kva.example",
+ "127.0.0.1",
+ ]
assert r.organization == "Foo Ltd."
r = certs.dummy_cert(
| An error occurred when trying to open a punycode domain
#### Problem Description
When trying to open a punycode domain, for example https://xn--80afnfom.xn--80ahmohdapg.xn--80asehdb/login, an error occurs in mitmproxy
mitmproxy log
```
[13:35:19.966][192.168.20.31:53287] client connect
[13:35:20.032][192.168.20.31:53287] server connect мойгаз.смородина.онлайн:443 (194.226.55.22:443)
[13:35:20.074] Addon error: DNSName values should be passed as an A-label string. This means unicode characters should be encoded via a library like idna.
Traceback (most recent call last):
File "mitmproxy\certs.py", line 271, in dummy_cert
File "ipaddress.py", line 54, in ip_address
ValueError: 'мойгаз.смородина.онлайн' does not appear to be an IPv4 or IPv6 address
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "cryptography\x509\general_name.py", line 84, in __init__
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "mitmproxy\addons\tlsconfig.py", line 177, in tls_start_client
File "mitmproxy\addons\tlsconfig.py", line 516, in get_cert
File "mitmproxy\certs.py", line 526, in get_cert
File "mitmproxy\certs.py", line 273, in dummy_cert
File "cryptography\x509\general_name.py", line 86, in __init__
ValueError: DNSName values should be passed as an A-label string. This means unicode characters should be encoded via a library like idna.
[13:35:20.078][192.168.20.31:53287] No TLS context was provided, failing connection.
[13:35:20.079][192.168.20.31:53287] client disconnect
[13:35:20.079][192.168.20.31:53287] server disconnect мойгаз.смородина.онлайн:443 (194.226.55.22:443)
```
#### Steps to reproduce the behavior:
1. Open in browser https://xn--80afnfom.xn--80ahmohdapg.xn--80asehdb/login
2. Result

#### System
```
Mitmproxy: 10.0.0 binary
Python: 3.11.4
OpenSSL: OpenSSL 3.0.7 1 Nov 2022
Platform: Windows-10-10.0.19045-SP0
```
| 2023-09-24T17:48:11 |
|
mitmproxy/mitmproxy | 6,428 | mitmproxy__mitmproxy-6428 | [
"6426"
] | 98d84f77cead76384b7e341ac3510d68422b2b1e | diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py
--- a/mitmproxy/addons/proxyauth.py
+++ b/mitmproxy/addons/proxyauth.py
@@ -40,7 +40,7 @@ def load(self, loader):
"username:pass",
"any" to accept any user/pass combination,
"@path" to use an Apache htpasswd file,
- or "ldap[s]:url_server_ldap[:port]:dn_auth:password:dn_subtree" for LDAP authentication.
+ or "ldap[s]:url_server_ldap[:port]:dn_auth:password:dn_subtree[?search_filter_key=...]" for LDAP authentication.
""",
)
@@ -213,6 +213,7 @@ class Ldap(Validator):
conn: ldap3.Connection
server: ldap3.Server
dn_subtree: str
+ filter_key: str
def __init__(self, proxyauth: str):
(
@@ -222,6 +223,7 @@ def __init__(self, proxyauth: str):
ldap_user,
ldap_pass,
self.dn_subtree,
+ self.filter_key,
) = self.parse_spec(proxyauth)
server = ldap3.Server(url, port=port, use_ssl=use_ssl)
conn = ldap3.Connection(server, ldap_user, ldap_pass, auto_bind=True)
@@ -229,7 +231,7 @@ def __init__(self, proxyauth: str):
self.server = server
@staticmethod
- def parse_spec(spec: str) -> tuple[bool, str, int | None, str, str, str]:
+ def parse_spec(spec: str) -> tuple[bool, str, int | None, str, str, str, str]:
try:
if spec.count(":") > 4:
(
@@ -245,6 +247,16 @@ def parse_spec(spec: str) -> tuple[bool, str, int | None, str, str, str]:
security, url, ldap_user, ldap_pass, dn_subtree = spec.split(":")
port = None
+ if "?" in dn_subtree:
+ dn_subtree, search_str = dn_subtree.split("?")
+ key, value = search_str.split("=")
+ if key == "search_filter_key":
+ search_filter_key = value
+ else:
+ raise ValueError
+ else:
+ search_filter_key = "cn"
+
if security == "ldaps":
use_ssl = True
elif security == "ldap":
@@ -252,14 +264,22 @@ def parse_spec(spec: str) -> tuple[bool, str, int | None, str, str, str]:
else:
raise ValueError
- return use_ssl, url, port, ldap_user, ldap_pass, dn_subtree
+ return (
+ use_ssl,
+ url,
+ port,
+ ldap_user,
+ ldap_pass,
+ dn_subtree,
+ search_filter_key,
+ )
except ValueError:
raise exceptions.OptionsError(f"Invalid LDAP specification: {spec}")
def __call__(self, username: str, password: str) -> bool:
if not username or not password:
return False
- self.conn.search(self.dn_subtree, f"(cn={username})")
+ self.conn.search(self.dn_subtree, f"({self.filter_key}={username})")
if self.conn.response:
c = ldap3.Connection(
self.server, self.conn.response[0]["dn"], password, auto_bind=True
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
@@ -127,7 +127,7 @@ def check():
"Please use `--proxyauth SPEC` instead.\n"
'SPEC Format: "username:pass", "any" to accept any user/pass combination,\n'
'"@path" to use an Apache htpasswd file, or\n'
- '"ldap[s]:url_server_ldap:dn_auth:password:dn_subtree" '
+ '"ldap[s]:url_server_ldap[:port]:dn_auth:password:dn_subtree[?search_filter_key=...]" '
"for LDAP authentication.".format(option)
)
| diff --git a/test/mitmproxy/addons/test_proxyauth.py b/test/mitmproxy/addons/test_proxyauth.py
--- a/test/mitmproxy/addons/test_proxyauth.py
+++ b/test/mitmproxy/addons/test_proxyauth.py
@@ -165,11 +165,25 @@ def test_configure(self, monkeypatch, tdata):
)
assert isinstance(pa.validator, proxyauth.Ldap)
+ ctx.configure(
+ pa,
+ proxyauth="ldap:localhost:1234:cn=default,dc=cdhdt,dc=com:password:dc=cdhdt,dc=com?search_filter_key=SamAccountName",
+ )
+ assert isinstance(pa.validator, proxyauth.Ldap)
+
with pytest.raises(
exceptions.OptionsError, match="Invalid LDAP specification"
):
ctx.configure(pa, proxyauth="ldap:test:test:test")
+ with pytest.raises(
+ exceptions.OptionsError, match="Invalid LDAP specification"
+ ):
+ ctx.configure(
+ pa,
+ proxyauth="ldap:localhost:1234:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com?key=1",
+ )
+
with pytest.raises(
exceptions.OptionsError, match="Invalid LDAP specification"
):
@@ -231,6 +245,7 @@ def test_handlers(self):
[
"ldaps:localhost:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com",
"ldap:localhost:1234:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com",
+ "ldap:localhost:1234:cn=default,dc=cdhdt,dc=com:password:ou=application,dc=cdhdt,dc=com?search_filter_key=cn",
],
)
def test_ldap(monkeypatch, spec):
diff --git a/test/mitmproxy/utils/test_arg_check.py b/test/mitmproxy/utils/test_arg_check.py
--- a/test/mitmproxy/utils/test_arg_check.py
+++ b/test/mitmproxy/utils/test_arg_check.py
@@ -35,7 +35,7 @@
"Please use `--proxyauth SPEC` instead.\n"
'SPEC Format: "username:pass", "any" to accept any user/pass combination,\n'
'"@path" to use an Apache htpasswd file, or\n'
- '"ldap[s]:url_server_ldap:dn_auth:password:dn_subtree" '
+ '"ldap[s]:url_server_ldap[:port]:dn_auth:password:dn_subtree[?search_filter_key=...]" '
"for LDAP authentication.",
),
(
| Insufficient flexibility of LDAP Proxy Auth
Insufficient flexibility of LDAP Proxy Auth
I noticed that in the Ldap Validator object, the username passed in during authentication queries will be set to cn. However, in our AD, CN is highly likely to be a Chinese name. Is there a solution to pass in other keys, such as SamAccountName
https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/addons/proxyauth.py#L212

| Not our focus right now, but happy to look at a PR for this. :) | 2023-10-30T13:39:57 |
mitmproxy/mitmproxy | 6,432 | mitmproxy__mitmproxy-6432 | [
"6420"
] | 640bb5377e24886342bacfc0c73e09ea71dc6956 | 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
@@ -700,6 +700,7 @@ def make_server_connection(self) -> layer.CommandGenerator[bool]:
return True
def handle_connect(self) -> layer.CommandGenerator[None]:
+ self.client_state = self.state_done
yield HttpConnectHook(self.flow)
if (yield from self.check_killed(False)):
return
| diff --git a/test/mitmproxy/proxy/layers/http/test_http.py b/test/mitmproxy/proxy/layers/http/test_http.py
--- a/test/mitmproxy/proxy/layers/http/test_http.py
+++ b/test/mitmproxy/proxy/layers/http/test_http.py
@@ -678,6 +678,7 @@ def test_server_unreachable(tctx, connect):
# Our API isn't ideal here, there is no error hook for CONNECT requests currently.
# We could fix this either by having CONNECT request go through all our regular hooks,
# or by adding dedicated ok/error hooks.
+ # See also: test_connect_unauthorized
playbook << http.HttpErrorHook(flow)
playbook >> reply()
playbook << SendData(
@@ -1632,6 +1633,42 @@ def test_connect_more_newlines(tctx):
assert nl().data_client() == b"\x16\x03\x03\x00\xb3\x01\x00\x00\xaf\x03\x03"
+def test_connect_unauthorized(tctx):
+ """Continue a connection after proxyauth returns a 407, https://github.com/mitmproxy/mitmproxy/issues/6420"""
+ playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))
+ flow = Placeholder(HTTPFlow)
+
+ def require_auth(f: HTTPFlow):
+ f.response = Response.make(
+ status_code=407, headers={"Proxy-Authenticate": f'Basic realm="mitmproxy"'}
+ )
+
+ assert (
+ playbook
+ >> DataReceived(tctx.client, b"CONNECT example.com:80 HTTP/1.1\r\n\r\n")
+ << http.HttpConnectHook(flow)
+ >> reply(side_effect=require_auth)
+ # This isn't ideal - we should probably have a custom CONNECT error hook here.
+ # See also: test_server_unreachable
+ << http.HttpResponseHook(flow)
+ >> reply()
+ << SendData(
+ tctx.client,
+ b"HTTP/1.1 407 Proxy Authentication Required\r\n"
+ b'Proxy-Authenticate: Basic realm="mitmproxy"\r\n'
+ b"content-length: 0\r\n\r\n",
+ )
+ >> DataReceived(
+ tctx.client,
+ b"CONNECT example.com:80 HTTP/1.1\r\n"
+ b"Proxy-Authorization: Basic dGVzdDp0ZXN0\r\n\r\n",
+ )
+ << http.HttpConnectHook(Placeholder(HTTPFlow))
+ >> reply()
+ << OpenConnection(Placeholder(Server))
+ )
+
+
def flows_tracked() -> int:
return sum(isinstance(x, HTTPFlow) for x in gc.get_objects())
| Proxyauth doesn't work on HTTPS on IOS
#### Problem Description
I'm trying to make my proxy have basic authentication. I'm running the proxy with the command `mitmdump --proxyauth ac:dc`, It starts on port `8080`. This all works well for cURL `curl -x ac:[email protected]:8080 https://httpbin.org`, but when I go on IOS
 (The password is there IOS just hides it in screenshots)
In my proxy terminal I get:
```
[17:39:17.187][192.168.1.28:59059] client connect
192.168.1.28:59059: CONNECT httpbin.org:443
<< 407 Proxy Authentication Required 129b
[17:39:17.221][192.168.1.28:59056] client disconnect
```
If I go to http://httpbin.org/ this is what I get:
```
[17:38:11.208][192.168.1.28:59047] server connect httpbin.org:80 (107.23.135.58:80)
192.168.1.28:59047: GET http://httpbin.org/flasgger_static/lib/jquery.min.js
<< 200 OK 83.6k
192.168.1.28:59045: GET http://httpbin.org/flasgger_static/swagger-ui-bundle.js
<< 200 OK 1.4m
192.168.1.28:59046: GET http://httpbin.org/flasgger_static/swagger-ui-standalone-preset.js
<< 200 OK 430k
[17:38:24.734][192.168.1.28:59044] client disconnect
192.168.1.28:59043: GET http://httpbin.org/
<< 200 OK 9.4k
[17:38:24.772][192.168.1.28:59049] client connect
192.168.1.28:59049: CONNECT fonts.googleapis.com:443
<< 407 Proxy Authentication Required 129b
```
Which works up until it gets a HTTPS request.
I found issue https://github.com/mitmproxy/mitmproxy/issues/5519 but it went stale and cannot find any answers / other issues related to this.
#### Steps to reproduce the behavior:
1. Setup your proxy with a username and password
2. Go to an IOS device (My version is 16.5) and connect to the proxy with the username/password in the authentication section
3. Examine terminal output
#### System Information
Mitmproxy: 10.1.1 binary
Python: 3.11.5
OpenSSL: OpenSSL 3.1.3 19 Sep 2023
Platform: Windows-10-10.0.19044-SP0
On my IPhone:
Model: IPhone 14 Pro
IOS Version: 16.5
| Can you run `mitmdump -v --proxyauth ac:dc` please? That should display the headers that are being sent with the CONNECT requests.
> Can you run `mitmdump -v --proxyauth ac:dc` please? That should display the headers that are being sent with the CONNECT requests.
HTTPS:
```
[07:00:09.099][192.168.1.28:57310] client connect
192.168.1.28:57310: CONNECT httpbin.org:443
Host: httpbin.org
Proxy-Connection: keep-alive
Connection: keep-alive
<< 407 Proxy Authentication Required 129b
Proxy-Authenticate: Basic realm="mitmproxy"
content-length: 129
[07:00:21.503][192.168.1.28:57306] client disconnect
```
And on an HTTP request:
```
[07:11:44.804][192.168.1.28:57409] server connect httpbin.org:80 (54.83.187.171:80)
192.168.1.28:57409: GET http://httpbin.org/
Host: httpbin.org
Proxy-Connection: keep-alive
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/604.1
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate
Connection: keep-alive
<< 200 OK 9.4k
Date: Fri, 27 Oct 2023 11:11:44 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 9593
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
```
I'm running into this too.
In Wireshark, I see the following:
```
CONNECT bag.itunes.apple.com:443 HTTP/1.1
Host: bag.itunes.apple.com
Proxy-Connection: keep-alive
Connection: keep-alive
HTTP/1.1 407 Proxy Authentication Required
Proxy-Authenticate: Basic realm="mitmproxy"
content-length: 129
<html><head><title>407 Proxy Authentication Required</title></head><body><h1>407 Proxy Authentication Required</h1></body></html>CONNECT bag.itunes.apple.com:443 HTTP/1.1
Host: bag.itunes.apple.com
Connection: keep-alive
Proxy-Authorization: Basic dGVzdDp0ZXN0
Proxy-Connection: keep-alive
```
It looks like the 407 is sent correctly from mitmproxy, and then the iOS device retries with the credentials attached. But, for some reason, mitmproxy does not appear to open a connection afterwards (there's no outgoing connection from the proxy, and the incoming connection to the proxy is just held open until Safari on iOS just gives up 30 seconds later).
There's nothing in the log. The same behaviour occurs even if `allow_hosts` is used to ignore hosts like this. Ordinary HTTP requests, which look substantially similar, succeed without issue.
This is *a regression*: mitmproxy 8.0.0 works fine, mitmproxy 9.0.0 does not.
...regression is from 8.0.0 (working) to 8.1.0 (not working). I'll run a bisect to see which commit broke things.
Bad commit is 035b3bf37d9785fef45e81eb9c0c47fc53ab24d2: "drop HTTP streams that are completed, fix #4456".
Maybe streams should only be dropped in mitmdump mode, and not while there's still a live TCP connection? However, I have not looked carefully at this commit to understand exactly how the drop logic works.
A minimal patch which works around this issue:
```
diff --git a/mitmproxy/proxy/layers/http/__init__.py b/mitmproxy/proxy/layers/http/__init__.py
index 7a2d0a305..b03b92e79 100644
--- a/mitmproxy/proxy/layers/http/__init__.py
+++ b/mitmproxy/proxy/layers/http/__init__.py
@@ -404,8 +404,7 @@ class HttpStream(layer.Layer):
if self.flow.response.trailers:
yield SendHttp(ResponseTrailers(self.stream_id, self.flow.response.trailers), self.context.client)
- if self.client_state == self.state_done:
- yield from self.flow_done()
+ yield from self.flow_done()
def flow_done(self):
if not self.flow.websocket:
```
This works on both 8.1.0 and on 10.1.1 (after compensating for whitespace changes) and restores HTTPS functionality. I'm not totally sure what the implication of this patch is, but it restores the pre-8.1.0 logic of calling the `flow_done` code unconditionally at the end of `send_response`.
Thank you two! That's clearly a protocol-level bug that needs a fix + a test case to make sure we don't regress again. Happy to look into this, but it likely won't be this week. Fortunately @nneonneo has found a workaround in the meantime. :)
> I'm not totally sure what the implication of this patch is
If mitmproxy is streaming request bodies, the entire response processing may be completed before the request has been completed. For example, a server may send a *413 Content Too Large* while the client is still uploading. In that case we want to avoid prematurely dropping the stream. The logic bug here is easy to fix (setting `self.client_state = self.state_done` right before https://github.com/mitmproxy/mitmproxy/blob/10.1.1/mitmproxy/proxy/layers/http/__init__.py#L759), but I actually want to go in and see if there are similar issues lurking somewhere.
Thanks again for the super helpful bisect! 😃 | 2023-10-31T13:10:23 |
mitmproxy/mitmproxy | 6,493 | mitmproxy__mitmproxy-6493 | [
"6329"
] | 9787871e6cadf397f94447c32dd4d397d937a954 | diff --git a/mitmproxy/flowfilter.py b/mitmproxy/flowfilter.py
--- a/mitmproxy/flowfilter.py
+++ b/mitmproxy/flowfilter.py
@@ -402,6 +402,7 @@ class FUrl(_Rex):
code = "u"
help = "URL"
is_binary = False
+ flags = re.IGNORECASE
# FUrl is special, because it can be "naked".
| diff --git a/test/mitmproxy/addons/test_blocklist.py b/test/mitmproxy/addons/test_blocklist.py
--- a/test/mitmproxy/addons/test_blocklist.py
+++ b/test/mitmproxy/addons/test_blocklist.py
@@ -22,20 +22,21 @@ def test_parse_spec_err(filter, err):
class TestBlockList:
@pytest.mark.parametrize(
- "filter,status_code",
+ "filter,request_url,status_code",
[
- (":~u example.org:404", 404),
- (":~u example.com:404", None),
- ("/!jpg/418", None),
- ("/!png/418", 418),
+ (":~u example.org:404", b"https://example.org/images/test.jpg", 404),
+ (":~u example.com:404", b"https://example.org/images/test.jpg", None),
+ (":~u test:404", b"https://example.org/images/TEST.jpg", 404),
+ ("/!jpg/418", b"https://example.org/images/test.jpg", None),
+ ("/!png/418", b"https://example.org/images/test.jpg", 418),
],
)
- def test_block(self, filter, status_code):
+ def test_block(self, filter, request_url, status_code):
bl = blocklist.BlockList()
with taddons.context(bl) as tctx:
tctx.configure(bl, block_list=[filter])
f = tflow.tflow()
- f.request.url = b"https://example.org/images/test.jpg"
+ f.request.url = request_url
bl.request(f)
if status_code is not None:
assert f.response.status_code == status_code
| uppercase breaks block_list
#### Problem Description
using these values for `block_list`
~~~
/~u AccountsSignInUi/444
/~u accountssigninui/444
~~~
neither one is blocking the expected URL:
~~~
https://accounts.google.com/v3/signin/_/AccountsSignInUi/data/batchexecute
~~~
this works:
~~~
/~u .ccounts.ign.n.i/444
~~~
why is uppercase character breaking the search?
#### System Information
tried with both:
~~~
> mitmproxy --version
Mitmproxy: 8.0.0 binary
Python: 3.10.2
OpenSSL: OpenSSL 1.1.1n 15 Mar 2022
Platform: Windows-10-10.0.18363-SP0
> mitmproxy --version
Mitmproxy: 10.0.0 binary
Python: 3.11.4
OpenSSL: OpenSSL 3.1.2 1 Aug 2023
Platform: Windows-10-10.0.18363-SP0
~~~
| I didn't verify this, but peeking at the code the issue should be here (I literally just ctrl+f for `lower`):
https://github.com/mitmproxy/mitmproxy/blob/7aa41a8467f73d86ad6ce5b95439c147a26896f9/mitmproxy/addons/blocklist.py#L27
If you are interested you can create a PR and add a case sensitive test here https://github.com/mitmproxy/mitmproxy/blob/7aa41a8467f73d86ad6ce5b95439c147a26896f9/test/mitmproxy/addons/test_blocklist.py
I am using a script like this as a workaround:
~~~py
from mitmproxy import http
def request(f: http.HTTPFlow) -> None:
if f.request.path == '/v3/signin/_/AccountsSignInUi/data/batchexecute':
f.kill()
~~~
| 2023-11-19T18:35:59 |
mitmproxy/mitmproxy | 6,549 | mitmproxy__mitmproxy-6549 | [
"6494",
"6546"
] | 1fcd0335d59c301d73d1b1ef676ecafcf520ab79 | diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py
--- a/mitmproxy/certs.py
+++ b/mitmproxy/certs.py
@@ -279,17 +279,15 @@ def dummy_cert(
x509.SubjectAlternativeName(ss), critical=not is_valid_commonname
)
- # we just use the same key as the CA for these certs, so put that in the SKI extension
- builder = builder.add_extension(
- x509.SubjectKeyIdentifier.from_public_key(privkey.public_key()),
- critical=False,
- )
- # add authority key identifier for the cacert issuing cert for greater acceptance by
- # client TLS libraries (such as OpenSSL 3.x)
+ # https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.1
builder = builder.add_extension(
x509.AuthorityKeyIdentifier.from_issuer_public_key(cacert.public_key()),
critical=False,
)
+ # If CA and leaf cert have the same Subject Key Identifier, SChannel breaks in funny ways,
+ # see https://github.com/mitmproxy/mitmproxy/issues/6494.
+ # https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.2 states
+ # that SKI is optional for the leaf cert, so we skip that.
cert = builder.sign(private_key=privkey, algorithm=hashes.SHA256()) # type: ignore
return Cert(cert)
| TLS issues with Windows/Schannel clients since 10.1.2
#### Problem Description
Only appeared at 10.1.2+, (10.1.1 and 9.0.1 are fine) so certification pinning is not related.
```
(venv) PS> mitmweb -p 58080
[08:44:07.112] HTTP(S) proxy listening at *:58080.
[08:44:07.112] Web server listening at http://127.0.0.1:8081/
[08:44:07.960] 403 GET //updates (127.0.0.1) 0.00ms
[08:44:08.457][[::1]:54408] client connect
[08:44:08.473][[::1]:54408] server connect login.microsoftonline.com:443 (20.190.151.7:443)
[08:44:08.916][[::1]:54408] Client TLS handshake failed. The client may not trust the proxy's certificate for login.microsoftonline.com (OpenSSL Error([('SSL routines', '', 'decryption failed or bad record mac')]))
[08:44:08.916][[::1]:54408] client disconnect
```
#### Steps to reproduce the behavior:
1. Installed latest Azure Powershell sdk (https://github.com/Azure/azure-powershell/releases)
2. mitmweb -p 58080
3. set proxy to http://localhost:58080: according to https://learn.microsoft.com/en-us/powershell/azure/az-powershell-proxy?view=azps-11.0.0
4. try run powershell command: Connect-AzAccount
#### System Information
Paste the output of "mitmproxy --version" here.
Mitmproxy: 10.1.2
Python: 3.12.0
OpenSSL: OpenSSL 3.1.4 24 Oct 2023
Platform: Windows-2022Server-10.0.20348-SP0
Separate private key used for dummy certificates
#### Description
Due to some Windows CryptoAPI validations same private key used in CA certificate and dummy certificate causes issues. A separate private key is generated during certificate store creation for dummy keys and CA private key is used for signing them.
This PR intends to fix [TLS issues with Windows/Schannel clients since 10.1.2](https://github.com/mitmproxy/mitmproxy/issues/6494)
#### Checklist
- [x] I have updated tests where applicable.
- [x] I have added an entry to the CHANGELOG.
| FYI: the working versions:
```
Mitmproxy: 10.1.1
Python: 3.12.0
OpenSSL: OpenSSL 3.1.4 24 Oct 2023
Platform: Windows-2022Server-10.0.20348-SP0
```
```
Mitmproxy: 9.0.1 binary
Python: 3.11.0
OpenSSL: OpenSSL 3.0.7 1 Nov 2022
Platform: Windows-10-10.0.20348-SP0
```
Thanks for bisecting versions! 🍰 😃
Looking at the changes between 10.1.1 and 10.1.2, the only reasonable candidate is https://github.com/mitmproxy/mitmproxy/commit/c3d2a9dac491f3588e8e53e542b8bf10d6d5b352. Now the big question is _why_ this is breaking things. Do you see any error message after running Connect-AzAccount?
find another way of reproducing, just `curl` like below
```bash
$ curl --proxy http://localhost:8080 https://login.microsoftonline.com --ssl-no-revoke -vvv
* processing: https://login.microsoftonline.com
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying [::1]:8080...
* Connected to localhost (::1) port 8080
* CONNECT tunnel: HTTP/1.1 negotiated
* allocate connect buffer
* Establish HTTP proxy tunnel to login.microsoftonline.com:443
> CONNECT login.microsoftonline.com:443 HTTP/1.1
> Host: login.microsoftonline.com:443
> User-Agent: curl/8.2.1
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection established
<
* CONNECT phase completed
* CONNECT tunnel established, response 200
* schannel: disabled automatic use of client certificate
* schannel: SEC_E_UNTRUSTED_ROOT (0x80090325) - The certificate chain was issued by an authority that is not trusted.
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
* Closing connection
* schannel: shutting down SSL/TLS connection with login.microsoftonline.com port 443
curl: (60) schannel: SEC_E_UNTRUSTED_ROOT (0x80090325) - The certificate chain was issued by an authority that is not trusted.
More details here: https://curl.se/docs/sslcerts.html
curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
```
double confirmed that I've already installed the p12 file.
And if create a mitmproxy 10.1.1 instance listening at another port, the curl works fine:
```bash
$ curl --proxy http://localhost:58080 https://login.microsoftonline.com --ssl-no-revoke -vvv
* processing: https://login.microsoftonline.com
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying [::1]:58080...
* Connected to localhost (::1) port 58080
* CONNECT tunnel: HTTP/1.1 negotiated
* allocate connect buffer
* Establish HTTP proxy tunnel to login.microsoftonline.com:443
> CONNECT login.microsoftonline.com:443 HTTP/1.1
> Host: login.microsoftonline.com:443
> User-Agent: curl/8.2.1
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection established
<
* CONNECT phase completed
* CONNECT tunnel established, response 200
* schannel: disabled automatic use of client certificate
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* using HTTP/1.x
> GET / HTTP/1.1
> Host: login.microsoftonline.com
> User-Agent: curl/8.2.1
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: no-store, no-cache
< Pragma: no-cache
< Content-Type: text/html; charset=utf-8
< Expires: -1
< Location: https://www.office.com/login#
< Strict-Transport-Security: max-age=31536000; includeSubDomains
< X-Content-Type-Options: nosniff
< P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
< x-ms-request-id: f9479479-f195-4812-8c27-3a1ada5d0900
< x-ms-ests-server: 2.1.16878.3 - SEASLR1 ProdSlices
< X-XSS-Protection: 0
< Set-Cookie: fpc=Al0BPsbEgcpPhdyJ__8_0no; expires=Sun, 31-Dec-2023 03:23:16 GMT; path=/; secure; HttpOnly; SameSite=None
< Set-Cookie: esctx=PAQABAAEAAAAmoFfGtYxvRrNriQdPKIZ-xr8ABw_NhXnYAy3wngJaQbI1rYi2GeQpX0PKisXCMny-cDMzV1nMtRt7reMep75dq1CZYiFcHtbFGPJ_eSbNXB4vUcwQeS9OUIMJCGa1SQtTu8ttklbdnWAti2q2yuW9q2Fb7jLbuzoztmHd9XLnyj9uyMpYzceNA773JM27Va0gAA; domain=.login.microsoftonline.com; path=/; secure; HttpOnly; SameSite=None
< Set-Cookie: x-ms-gateway-slice=estsfd; path=/; secure; samesite=none; httponly
< Set-Cookie: stsservicecookie=estsfd; path=/; secure; samesite=none; httponly
< Date: Fri, 01 Dec 2023 03:23:15 GMT
< Content-Length: 146
<
{ [146 bytes data]
100 146 100 146 0 0 139 0 0:00:01 0:00:01 --:--:-- 139<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="https://www.office.com/login#">here</a>.</h2>
</body></html>
* Connection #0 to host localhost left intact
```
I've been banging my head against this problem for a while now. I had previously posted to a [discussion thread](https://github.com/mitmproxy/mitmproxy/discussions/6435) hoping that someone had encountered this.
From what I've seen this seems to be isolated to Windows CryptoAPI, as browsers are not affected and correctly trust an installed certificate. Interestingly, IIS hosted projects don't exhibit the problem. It would seem that programs that circumvent windows build-in certificate checking (or maybe use some special parameters) work properly.
I will be reunited with my Windows machine some time next week. In the meantime, if someone could verify that reverting https://github.com/mitmproxy/mitmproxy/commit/c3d2a9dac491f3588e8e53e542b8bf10d6d5b352 does indeed fix this, that'd be great. Of course, a PR with a proper fix is would _fantastic_. :)
Similarly, I encountered this with a Windows application that uses the system WinHttp API (not for browsing, just HTTPS requests to different API services).
> I will be reunited with my Windows machine some time next week. In the meantime, if someone could verify that reverting [c3d2a9d](https://github.com/mitmproxy/mitmproxy/commit/c3d2a9dac491f3588e8e53e542b8bf10d6d5b352) does indeed fix this, that'd be great. Of course, a PR with a proper fix is would _fantastic_. :)
I can try reverting the change during the weekend.
> if someone could verify that reverting https://github.com/mitmproxy/mitmproxy/commit/c3d2a9dac491f3588e8e53e542b8bf10d6d5b352 does indeed fix this
I checked version 10.1.5 with the lines from this commit commented out - and now everything worked correctly.
Ok, I did some testing and I *think* I know the issue.
What I've noticed is that we are reusing the same private key from CA certificate for domain certification. This means that both subject and authority key identifiers are the same (and the same as root CA subject key identifier). What I *think* is happening is that Windows CryptoAPI validates the subject against itself instead of its issuer - mitmproxy root CA. It tracks with my previous testing where .NET `HttpClient` fails [even in custom trust mode](https://github.com/mitmproxy/mitmproxy/discussions/6435#discussioncomment-7588209).
We could generate a separate private key (either temporary or persisted). A temporary key could be stored in memory and reused during the lifetime of the session, a persistent key could be stored in the same manner as root CA certificates are stored now.
I can look into it tomorrow, however I don't know how much time I'll have to make a proper PR for this.
**EDIT:**
Ok, so I've also looked at the code some more and it seems to me that we already have a mechanism to persist temporary keys in the certificate store. As it is now certificate store creation procedure `from_store` loads persisted certificates and sets defaults (CA values), these defaults are later used for generating dummy certificates. Correct me if I'm wrong, but we should be able to change the defaults here with a newly generated private key and it should work.
**EDIT 2:**
It seems to work just fine, made a quick fork and tested it on my Windows laptop. I'm not sure how exactly the pull request process works around here (I obviously can't create branches on this repository), but I'd be willing to spend some more time and update relevant use cases in tests and examples during the next week or so.
| 2023-12-12T17:57:55 |
|
mitmproxy/mitmproxy | 6,581 | mitmproxy__mitmproxy-6581 | [
"6529"
] | 770443ee8928bf2948662548c8666024439f8449 | diff --git a/mitmproxy/proxy/mode_servers.py b/mitmproxy/proxy/mode_servers.py
--- a/mitmproxy/proxy/mode_servers.py
+++ b/mitmproxy/proxy/mode_servers.py
@@ -234,7 +234,10 @@ def listen_addrs(self) -> tuple[Address, ...]:
if isinstance(s, mitmproxy_rs.UdpServer):
addrs.append(s.getsockname())
else:
- addrs.extend(sock.getsockname() for sock in s.sockets)
+ try:
+ addrs.extend(sock.getsockname() for sock in s.sockets)
+ except OSError: # pragma: no cover
+ pass # this can fail during shutdown, see https://github.com/mitmproxy/mitmproxy/issues/6529
return tuple(addrs)
async def _start(self) -> None:
| Getting errors after terminating from mitmproxy console
#### Problem Description
Getting error log after terminating from the mitmproxy console when executing the io-write-file.py
#### Steps to reproduce the behavior:
1. Run the cmd : mitmproxy io-write-file.py "/path/to/dump/file"
2. After running a while then quit from mitmproxy console.
3. In terminal able to see errors.
#### System Information
Mitmproxy: 10.1.5
Python: 3.11.5
OpenSSL: OpenSSL 3.1.4 24 Oct 2023
Platform: Windows-10-10.0.22631-SP0

| 2024-01-04T13:21:29 |
||
mitmproxy/mitmproxy | 6,587 | mitmproxy__mitmproxy-6587 | [
"6586"
] | ae00e82c3a0733f82db476a0496349a4969a86c0 | diff --git a/mitmproxy/proxy/mode_servers.py b/mitmproxy/proxy/mode_servers.py
--- a/mitmproxy/proxy/mode_servers.py
+++ b/mitmproxy/proxy/mode_servers.py
@@ -372,7 +372,7 @@ async def _start(self) -> None:
_ = mitmproxy_rs.pubkey(self.server_key)
self._server = await mitmproxy_rs.start_wireguard_server(
- host or "127.0.0.1",
+ host or "0.0.0.0",
port,
self.server_key,
[p],
| mitmproxy: 10.2: WireGuard Mode Does Not Receive Connections
#### Problem Description
It looks like commit 6e38a56f4 Thu Jan 4 10:53:13 2024 +0100 implement UDP streams (and all future commits) has changed/broken something in the wireguard proxy mode. Prior commits work as expected.
#### Steps to reproduce the behavior:
1. Build 6e38a56f4 or tag 10.2.0
2. ./mitmdump --set block_global=false --mode 'wireguard:/home/admin/.mitmproxy/wireguard.conf'
3. Then curl or visit web page from client running wireguard client , mitmproxy server does not accept the request
When mitmdump (version 6e38a56f4 or tag 10.2.0) starts the following is printed
```
./mitmdump --set block_global=false --mode 'wireguard:/home/admin/.mitmproxy/wireguard.conf'
[23:47:56.530] ------------------------------------------------------------
[Interface]
PrivateKey = ...
Address = 10.0.0.1/32
DNS = 10.0.0.53
[Peer]
PublicKey = ...
AllowedIPs = 0.0.0.0/0
Endpoint = a.b.c.d:60000
------------------------------------------------------------
[23:47:56.530] WireGuard server listening at 127.0.0.1:60000.
```
#### System Information
./mitmdump --version Mitmproxy: 11.0.0.dev (+9, commit 6e38a56)
Python: 3.11.2
OpenSSL: OpenSSL 3.1.2 1 Aug 2023
Platform: Linux-6.1.0-15-cloud-arm64-aarch64-with-glibc2.36
When commit ed532e927 is run the following is logged - this is the expected output and in this case mitmproxy works as expected in wg mode.
```
./mitmdump --set block_global=false --mode 'wireguard:/home/admin/.mitmproxy/wireguard.conf'
[23:45:25.620] Initializing WireGuard server ...
[23:45:25.621] WireGuard server listening for UDP connections on 0.0.0.0:60000 and [::]:60000 ...
[23:45:25.621] WireGuard server successfully initialized.
[23:45:25.622] ------------------------------------------------------------
[Interface]
PrivateKey = ...
Address = 10.0.0.1/32
DNS = 10.0.0.53
[Peer]
PublicKey = ...
AllowedIPs = 0.0.0.0/0
Endpoint = a.b.c.d:60000
------------------------------------------------------------
[23:45:25.622] WireGuard server listening at *:60000.
[23:45:26.335][10.0.0.2:52756] client connect
...usual logs...
```
#### System Information
Mitmproxy: 11.0.0.dev (+8, commit ed532e9)
Python: 3.11.2
OpenSSL: OpenSSL 3.1.2 1 Aug 2023
Platform: Linux-6.1.0-15-cloud-arm64-aarch64-with-glibc2.36
| Thanks! It looks like I accidentally changed the default listening address to `127.0.0.1` instead of binding to all interfaces. The workaround is to specify it explicitly:
```
mitmweb --mode [email protected]:51820
```
Let's ship a patch release for this... | 2024-01-06T13:19:48 |
|
mitmproxy/mitmproxy | 6,594 | mitmproxy__mitmproxy-6594 | [
"6325"
] | 4101e8aeef770df29a7f8cf8d74c88c2ac6c04ba | diff --git a/mitmproxy/addons/next_layer.py b/mitmproxy/addons/next_layer.py
--- a/mitmproxy/addons/next_layer.py
+++ b/mitmproxy/addons/next_layer.py
@@ -218,18 +218,24 @@ def _ignore_connection(
) and context.server.address == ("10.0.0.53", 53):
return False
hostnames: list[str] = []
- if context.server.peername and (peername := context.server.peername[0]):
- hostnames.append(peername)
- if context.server.address and (server_address := context.server.address[0]):
- hostnames.append(server_address)
- # If we already have a destination address, we can also check for HTTP Host headers.
- # But we do need the destination, otherwise we don't know where this connection is going to.
+ if context.server.peername:
+ host, port = context.server.peername
+ hostnames.append(f"{host}:{port}")
+ if context.server.address:
+ host, port = context.server.address
+ hostnames.append(f"{host}:{port}")
+
+ # We also want to check for TLS SNI and HTTP host headers, but in order to ignore connections based on that
+ # they must have a destination address. If they don't, we don't know how to establish an upstream connection
+ # if we ignore.
if host_header := self._get_host_header(context, data_client, data_server):
+ if not re.search(r":\d+$", host_header):
+ host_header = f"{host_header}:{port}"
hostnames.append(host_header)
- if (
- client_hello := self._get_client_hello(context, data_client)
- ) and client_hello.sni:
- hostnames.append(client_hello.sni)
+ if (
+ client_hello := self._get_client_hello(context, data_client)
+ ) and client_hello.sni:
+ hostnames.append(f"{client_hello.sni}:{port}")
if not hostnames:
return False
@@ -271,7 +277,9 @@ def _get_host_header(
rb"[A-Z]{3,}.+HTTP/", data_client, re.IGNORECASE
)
if host_header_expected:
- if m := re.search(rb"\r\n(?:Host: (.+))?\r\n", data_client, re.IGNORECASE):
+ if m := re.search(
+ rb"\r\n(?:Host:\s+(.+?)\s*)?\r\n", data_client, re.IGNORECASE
+ ):
if host := m.group(1):
return host.decode("utf-8", "surrogateescape")
else:
| diff --git a/test/mitmproxy/addons/test_next_layer.py b/test/mitmproxy/addons/test_next_layer.py
--- a/test/mitmproxy/addons/test_next_layer.py
+++ b/test/mitmproxy/addons/test_next_layer.py
@@ -117,7 +117,25 @@ def test_configure(self):
["example.com"], [], "tcp", "example.com", b"", True, id="address"
),
pytest.param(
- ["1.2.3.4"], [], "tcp", "example.com", b"", True, id="ip address"
+ ["192.0.2.1"], [], "tcp", "example.com", b"", True, id="ip address"
+ ),
+ pytest.param(
+ ["example.com:443"],
+ [],
+ "tcp",
+ "example.com",
+ b"",
+ True,
+ id="port matches",
+ ),
+ pytest.param(
+ ["example.com:123"],
+ [],
+ "tcp",
+ "example.com",
+ b"",
+ False,
+ id="port does not match",
),
pytest.param(
["example.com"],
@@ -177,7 +195,7 @@ def test_configure(self):
["example.com"],
[],
"tcp",
- None,
+ "192.0.2.1",
client_hello_with_extensions,
True,
id="sni",
@@ -186,7 +204,7 @@ def test_configure(self):
["example.com"],
[],
"tcp",
- None,
+ "192.0.2.1",
client_hello_with_extensions[:-5],
NeedsMoreData,
id="incomplete client hello",
@@ -195,7 +213,7 @@ def test_configure(self):
["example.com"],
[],
"tcp",
- None,
+ "192.0.2.1",
client_hello_no_extensions[:9] + b"\x00" * 200,
False,
id="invalid client hello",
@@ -213,7 +231,7 @@ def test_configure(self):
["example.com"],
[],
"udp",
- None,
+ "192.0.2.1",
dtls_client_hello_with_extensions,
True,
id="dtls sni",
@@ -222,7 +240,7 @@ def test_configure(self):
["example.com"],
[],
"udp",
- None,
+ "192.0.2.1",
dtls_client_hello_with_extensions[:-5],
NeedsMoreData,
id="incomplete dtls client hello",
@@ -231,7 +249,7 @@ def test_configure(self):
["example.com"],
[],
"udp",
- None,
+ "192.0.2.1",
dtls_client_hello_with_extensions[:9] + b"\x00" * 200,
False,
id="invalid dtls client hello",
@@ -240,7 +258,7 @@ def test_configure(self):
["example.com"],
[],
"udp",
- None,
+ "192.0.2.1",
quic_client_hello,
True,
id="quic sni",
@@ -297,7 +315,7 @@ def test_ignore_connection(
ctx.client.transport_protocol = transport_protocol
if server_address:
ctx.server.address = (server_address, 443)
- ctx.server.peername = ("1.2.3.4", 443)
+ ctx.server.peername = ("192.0.2.1", 443)
if result is NeedsMoreData:
with pytest.raises(NeedsMoreData):
nl._ignore_connection(ctx, data_client, b"")
| `ignore_hosts` and `allow_hosts` are not matched against `host:port` format
#### Problem Description
Documentation [Ignoring Domains](https://docs.mitmproxy.org/stable/howto-ignoredomains/) says that `ignore_hosts` is matched against `host:port` string.
> The `ignore_hosts` option allows you to specify a regex which is matched against a `host:port` string (e.g. “example.com:443”) of a connection.
But it seems that in the current implementation `ignore_hosts` is matched against only `host` (and `ip`) string.
https://github.com/mitmproxy/mitmproxy/blob/7aa41a8467f73d86ad6ce5b95439c147a26896f9/mitmproxy/addons/next_layer.py#L214-L222
This behaviour is consistent with the [Options](https://docs.mitmproxy.org/stable/concepts-options/) page.
> The supplied value is interpreted as a regular expression and matched on the ip or the hostname.
To ignore specific services, the `host:port` format is important.
IMO, for backward compatibility, it should be matched against both `host:port` and `host` string.
This issue was introduced in v7.
| | `host` | `host:port` |
|-|-|-|
| v6.0.2 | not match | match |
| v7.0.0 | match | not match |
#### Steps to reproduce the behavior:
1. `mitmproxy --ignore-hosts '^example.com:443$'`
2. `curl -x localhost:8080 -k https://example.com/`
#### System Information
```
Mitmproxy: 10.0.0 binary
Python: 3.11.4
OpenSSL: OpenSSL 3.1.2 1 Aug 2023
Platform: Linux-6.4.10-arch1-1-x86_64-with-glibc2.38
```
| 2024-01-09T09:24:14 |
|
mitmproxy/mitmproxy | 6,605 | mitmproxy__mitmproxy-6605 | [
"6604"
] | 4101e8aeef770df29a7f8cf8d74c88c2ac6c04ba | diff --git a/mitmproxy/addons/clientplayback.py b/mitmproxy/addons/clientplayback.py
--- a/mitmproxy/addons/clientplayback.py
+++ b/mitmproxy/addons/clientplayback.py
@@ -156,10 +156,10 @@ def __init__(self):
self.replay_tasks = set()
def running(self):
+ self.options = ctx.options
self.playback_task = asyncio_utils.create_task(
self.playback(), name="client playback"
)
- self.options = ctx.options
async def done(self):
if self.playback_task:
| AttributeError: 'ClientPlayback' object has no attribute 'options'
#### Problem Description
Client playback does not seem to work anymore, since 10.2.0.
On 10.1.6 it still works.
I am getting the following error:
>Traceback (most recent call last):
File "mitmproxy/addons/clientplayback.py", line 177, in playback
AttributeError: 'ClientPlayback' object has no attribute 'options'
#### Steps to reproduce the behavior:
1. Save a recorded flow
2. Replay it using `mitmdump -C stored.flow`
3. See error
#### System Information
Mitmproxy: 10.2.1 binary
Python: 3.12.1
OpenSSL: OpenSSL 3.1.4 24 Oct 2023
Platform: macOS-14.2.1-x86_64-i386-64bit
| 2024-01-17T16:28:33 |
||
mitmproxy/mitmproxy | 6,609 | mitmproxy__mitmproxy-6609 | [
"6608"
] | 08eb515635c8fd6d66d3a2364b7e9b5f4ccc601e | 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
@@ -528,8 +528,8 @@ def flow_done(self) -> layer.CommandGenerator[None]:
yield commands.Log(
f"{self.debug}[http] upgrading to {self.child_layer}", DEBUG
)
- yield from self.child_layer.handle_event(events.Start())
self._handle_event = self.passthrough
+ yield from self.child_layer.handle_event(events.Start())
else:
yield DropStream(self.stream_id)
@@ -749,8 +749,8 @@ def handle_connect_finish(self):
if 200 <= self.flow.response.status_code < 300:
self.child_layer = self.child_layer or layer.NextLayer(self.context)
- yield from self.child_layer.handle_event(events.Start())
self._handle_event = self.passthrough
+ yield from self.child_layer.handle_event(events.Start())
yield SendHttp(
ResponseHeaders(self.stream_id, self.flow.response, True),
self.context.client,
| mitmproxy crashed error after application connects to a websocket
### Discussed in https://github.com/mitmproxy/mitmproxy/discussions/6601
<div type='discussions-op-text'>
<sup>Originally posted by **Botytec** January 14, 2024</sup>
im running mitmproxy in local mode that is proxying only one application, everytime that application connects to a websocket server i get this error
mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy\proxy\server.py", line 380, in server_event
File "mitmproxy\proxy\layer.py", line 156, in handle_event
File "mitmproxy\proxy\layer.py", line 269, in handle_event
File "mitmproxy\proxy\layer.py", line 156, in handle_event
File "mitmproxy\proxy\tunnel.py", line 98, in _handle_event
File "mitmproxy\proxy\layers\tls.py", line 485, in event_to_child
File "mitmproxy\proxy\tunnel.py", line 153, in event_to_child
File "mitmproxy\proxy\layer.py", line 156, in handle_event
File "mitmproxy\proxy\tunnel.py", line 98, in _handle_event
File "mitmproxy\proxy\tunnel.py", line 153, in event_to_child
File "mitmproxy\proxy\layer.py", line 156, in handle_event
File "mitmproxy\proxy\layers\http\__init__.py", line 880, in _handle_event
File "mitmproxy\proxy\layers\http\__init__.py", line 936, in event_to_child
File "mitmproxy\proxy\layer.py", line 147, in handle_event
File "mitmproxy\proxy\utils.py", line 26, in _check_event_type
AssertionError: Unexpected event type at HttpStream._handle_event: Expected Start|HttpEvent, got Reply(WebsocketStartHook(flow=<HTTPFlow
</div>
| 2024-01-21T13:46:42 |
||
mitmproxy/mitmproxy | 6,619 | mitmproxy__mitmproxy-6619 | [
"6603"
] | 6c7089f7a3bdc2f13017599fc9edfe247af65b67 | diff --git a/mitmproxy/contentviews/graphql.py b/mitmproxy/contentviews/graphql.py
--- a/mitmproxy/contentviews/graphql.py
+++ b/mitmproxy/contentviews/graphql.py
@@ -30,7 +30,12 @@ def is_graphql_query(data):
def is_graphql_batch_query(data):
- return isinstance(data, list) and isinstance(data[0], dict) and "query" in data[0]
+ return (
+ isinstance(data, list)
+ and len(data) > 0
+ and isinstance(data[0], dict)
+ and "query" in data[0]
+ )
class ViewGraphQL(base.View):
| diff --git a/test/mitmproxy/contentviews/test_graphql.py b/test/mitmproxy/contentviews/test_graphql.py
--- a/test/mitmproxy/contentviews/test_graphql.py
+++ b/test/mitmproxy/contentviews/test_graphql.py
@@ -19,6 +19,7 @@ def test_render_priority():
assert 0 == v.render_priority(
b"""[{"xquery": "query P { \\n }"}]""", content_type="application/json"
)
+ assert 0 == v.render_priority(b"""[]""", content_type="application/json")
assert 0 == v.render_priority(b"}", content_type="application/json")
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
@@ -78,6 +78,22 @@ def test_format_json():
[("text", " "), ("text", "]"), ("text", "")],
[("text", ""), ("text", "}")],
]
+ assert list(json.format_json({"list": []})) == [
+ [("text", "{"), ("text", "")],
+ [
+ ("text", " "),
+ ("Token_Name_Tag", '"list"'),
+ ("text", ": "),
+ ("text", "[]"),
+ ("text", ""),
+ ],
+ [("text", ""), ("text", "}")],
+ ]
+ assert list(json.format_json(None)) == [[("Token_Keyword_Constant", "null")]]
+ assert list(json.format_json(True)) == [[("Token_Keyword_Constant", "true")]]
+ assert list(json.format_json(1)) == [[("Token_Literal_Number", "1")]]
+ assert list(json.format_json("test")) == [[("Token_Literal_String", '"test"')]]
+ assert list(json.format_json([])) == [[("text", "[]")]]
def test_view_json():
@@ -88,6 +104,7 @@ def test_view_json():
assert v(b"[1, 2, 3, 4, 5]")
assert v(b'{"foo" : 3}')
assert v(b'{"foo": true, "nullvalue": null}')
+ assert v(b"[]")
@given(binary())
| `Couldn't parse: falling back to Raw` for empty JSON array
#### Problem Description
The following response packet:
```
HTTP/2.0 200
date: Sun, 14 Jan 2024 23:30:12 GMT
content-type: application/json; charset=utf-8
content-length: 2
server: nginx/1.18.0 (Ubuntu)
cache-control: no-store
x-amzn-trace-id: [REDACTED]
x-frame-options: DENY
set-cookie: [REDACTED]
strict-transport-security: max-age=31536000
[]
```
is displayed as "Couldn't parse: falling back to Raw", but it's clearly JSON from the content type and an empty array is a normal JSON response that shouldn't trigger this warning. In fact, top level `null`, booleans, numbers and strings should be just fine as well, I don't know if they do or don't.
#### Steps to reproduce the behavior:
Set up a JSON endpoint that returns `[]` with a `content-type: application/json; charset=utf-8` header and open it in mitmproxy
#### System Information
```
Mitmproxy: 10.2.1 binary
Python: 3.12.1
OpenSSL: OpenSSL 3.1.4 24 Oct 2023
Platform: macOS-14.2.1-x86_64-arm-64bit
```
| Thanks! Looks like an edge case for the empty array, the following all work: `[1]`, `"foo"` and `null`
@Prinzhorn I would like to fix this. Could you show me the part(s) of the codebase where this is handled?
@haanhvu sure, it's probably somewhere in https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/contentviews/json.py . I don't think the parsing of the JSON is failing but the algorithm that colorizes it (`format_json`).
I'd start with adding a failing test to https://github.com/mitmproxy/mitmproxy/blob/main/test/mitmproxy/contentviews/test_json.py
Edit: here's how you locally set everything up https://github.com/mitmproxy/mitmproxy/blob/main/CONTRIBUTING.md | 2024-01-27T14:15:07 |
mitmproxy/mitmproxy | 6,648 | mitmproxy__mitmproxy-6648 | [
"6647"
] | 1a02ebb89f6765d827f2fe0086dfe5960eb6e093 | diff --git a/mitmproxy/addons/dns_resolver.py b/mitmproxy/addons/dns_resolver.py
--- a/mitmproxy/addons/dns_resolver.py
+++ b/mitmproxy/addons/dns_resolver.py
@@ -26,7 +26,9 @@ async def resolve_question_by_name(
ip: Callable[[str], ipaddress.IPv4Address | ipaddress.IPv6Address],
) -> Iterable[dns.ResourceRecord]:
try:
- addrinfos = await loop.getaddrinfo(host=question.name, port=0, family=family)
+ addrinfos = await loop.getaddrinfo(
+ host=question.name, port=0, family=family, type=socket.SOCK_STREAM
+ )
except socket.gaierror as e:
if e.errno == socket.EAI_NONAME:
raise ResolveError(dns.response_codes.NXDOMAIN)
| diff --git a/test/mitmproxy/addons/test_dns_resolver.py b/test/mitmproxy/addons/test_dns_resolver.py
--- a/test/mitmproxy/addons/test_dns_resolver.py
+++ b/test/mitmproxy/addons/test_dns_resolver.py
@@ -41,18 +41,18 @@ async def getnameinfo(self, socketaddr: Address, flags: int = 0):
e.errno = socket.EAI_NONAME
raise e
- async def getaddrinfo(self, host: str, port: int, *, family: int):
+ async def getaddrinfo(self, host: str, port: int, *, family: int, type: int):
e = socket.gaierror()
e.errno = socket.EAI_NONAME
if family == socket.AF_INET:
if host == "dns.google":
- return [(socket.AF_INET, None, None, None, ("8.8.8.8", port))]
+ return [(socket.AF_INET, type, None, None, ("8.8.8.8", port))]
elif family == socket.AF_INET6:
if host == "dns.google":
return [
(
socket.AF_INET6,
- None,
+ type,
None,
None,
("2001:4860:4860::8888", port, None, None),
diff --git a/test/mitmproxy/addons/test_proxyserver.py b/test/mitmproxy/addons/test_proxyserver.py
--- a/test/mitmproxy/addons/test_proxyserver.py
+++ b/test/mitmproxy/addons/test_proxyserver.py
@@ -270,9 +270,9 @@ class DummyResolver:
async def dns_request(self, flow: dns.DNSFlow) -> None:
flow.response = await dns_resolver.resolve_message(flow.request, self)
- async def getaddrinfo(self, host: str, port: int, *, family: int):
+ async def getaddrinfo(self, host: str, port: int, *, family: int, type: int):
if family == socket.AF_INET and host == "dns.google":
- return [(socket.AF_INET, None, None, None, ("8.8.8.8", port))]
+ return [(socket.AF_INET, type, None, None, ("8.8.8.8", port))]
e = socket.gaierror()
e.errno = socket.EAI_NONAME
raise e
| Duplicate answers in DNS queries
#### Problem Description
Two duplicate records are returned for each unique A/AAAA record in a DNS query when using DNS mode.
#### Steps to reproduce the behavior:
##### Without mitmproxy
1. Run `dig +short google.com`
2. Correct output: `142.250.193.206`
##### With mitmproxy
1. Start mitmproxy `mitmproxy --mode dns@53535`
2. Run `dig @127.0.0.1 -p 53535 +short google.com`
3. Output with duplicates:
```
142.250.193.206
142.250.193.206
142.250.193.206
```
#### System Information
```
Mitmproxy: 11.0.0.dev (+19, commit d638213)
Python: 3.12.1
OpenSSL: OpenSSL 3.1.4 24 Oct 2023
Platform: Linux-6.6.14-200.fc39.x86_64-x86_64-with-glibc2.38
```
#### Additional Notes
This is happening because the `dns_resolver` addon calls `getaddrinfo` here:
https://github.com/mitmproxy/mitmproxy/blob/1a02ebb89f6765d827f2fe0086dfe5960eb6e093/mitmproxy/addons/dns_resolver.py#L29
Which is returning one tuple each for UDP, TCP and a raw socket.
We could just do the following since I assume all requests are currently using UDP:
```python
addrinfos = await loop.getaddrinfo(host=question.name, port=0, family=family, type=socket.SOCK_DGRAM)
```
What do you think?
| Yes, please send a PR! We eventually should really support DNS-over-TCP, but this is a good mitigation for now. | 2024-02-06T15:39:48 |
mitmproxy/mitmproxy | 6,692 | mitmproxy__mitmproxy-6692 | [
"4476"
] | 240a286b2a3cedd0193b660e5217adfa46bb82b3 | diff --git a/mitmproxy/addons/dumper.py b/mitmproxy/addons/dumper.py
--- a/mitmproxy/addons/dumper.py
+++ b/mitmproxy/addons/dumper.py
@@ -18,6 +18,7 @@
from mitmproxy import http
from mitmproxy.contrib import click as miniclick
from mitmproxy.net.dns import response_codes
+from mitmproxy.options import CONTENT_VIEW_LINES_CUTOFF
from mitmproxy.tcp import TCPFlow
from mitmproxy.tcp import TCPMessage
from mitmproxy.udp import UDPFlow
@@ -54,12 +55,12 @@ def load(self, loader):
"flow_detail",
int,
1,
- """
+ f"""
The display detail level for flows in mitmdump: 0 (quiet) to 4 (very verbose).
0: no output
1: shortened request URL with response status code
2: full request URL with response status code and HTTP headers
- 3: 2 + truncated response content, content of WebSocket and TCP messages
+ 3: 2 + truncated response content, content of WebSocket and TCP messages (content_view_lines_cutoff: {CONTENT_VIEW_LINES_CUTOFF})
4: 3 + nothing is truncated
""",
)
@@ -125,7 +126,9 @@ def _echo_message(
logging.debug(error)
if ctx.options.flow_detail == 3:
- lines_to_echo = itertools.islice(lines, 70)
+ lines_to_echo = itertools.islice(
+ lines, ctx.options.content_view_lines_cutoff
+ )
else:
lines_to_echo = lines
| diff --git a/test/mitmproxy/addons/test_dumper.py b/test/mitmproxy/addons/test_dumper.py
--- a/test/mitmproxy/addons/test_dumper.py
+++ b/test/mitmproxy/addons/test_dumper.py
@@ -97,7 +97,7 @@ def test_simple():
def test_echo_body():
f = tflow.tflow(resp=True)
f.response.headers["content-type"] = "text/html"
- f.response.content = b"foo bar voing\n" * 100
+ f.response.content = b"foo bar voing\n" * 600
sio = io.StringIO()
d = dumper.Dumper(sio)
@@ -108,6 +108,21 @@ def test_echo_body():
assert "cut off" in t
+def test_echo_body_custom_cutoff():
+ f = tflow.tflow(resp=True)
+ f.response.headers["content-type"] = "text/html"
+ f.response.content = b"foo bar voing\n" * 4
+
+ sio = io.StringIO()
+ d = dumper.Dumper(sio)
+ with taddons.context(d) as ctx:
+ ctx.configure(d, flow_detail=3)
+ ctx.configure(d, content_view_lines_cutoff=3)
+ d._echo_message(f.response, f)
+ t = sio.getvalue()
+ assert "cut off" in t
+
+
def test_echo_trailer():
sio = io.StringIO()
d = dumper.Dumper(sio)
@@ -118,7 +133,7 @@ def test_echo_trailer():
f.request.headers["content-type"] = "text/html"
f.request.headers["transfer-encoding"] = "chunked"
f.request.headers["trailer"] = "my-little-request-trailer"
- f.request.content = b"some request content\n" * 100
+ f.request.content = b"some request content\n" * 600
f.request.trailers = Headers(
[(b"my-little-request-trailer", b"foobar-request-trailer")]
)
| Dumper Addon: make the number of printed lines configurable when using `flow_detail = 3`
I try to dump full traffic on stdout using mitmdump, but when response body has more than about 80 or 90 lines on stdout appear (cut off) and all other lines are lost,
I use this command:
*mitmdump --set flow_detail=3 --set content_view_lines_cutoff=2000* <br><br>
The exact behavior is described [here](https://discourse.mitmproxy.org/t/mitmdump-cutting-off-responses/1714) on old mitmproxy forum: unfortunately there was no response
@debian-10:~$ Scaricati/mitmdump --version
Mitmproxy: 6.0.2 binary
Python: 3.9.1
OpenSSL: OpenSSL 1.1.1i 8 Dec 2020
Platform: Linux-4.19.0-14-amd64-x86_64-with-glibc2.28
| I'm not sure why it's that way, but it happens here
https://github.com/mitmproxy/mitmproxy/blob/8178f6c77b715cd342f8be161d5ca5da8938645c/mitmproxy/addons/dumper.py#L110-L113
but all calls to `_echo_message` are already guarded with `if ctx.options.flow_detail >= 3:` so the `else` will _never_ be reached. Edit: ok, technically if `flow_details` was `4` or something :roll_eyes:
It's been this way since the beginning https://github.com/mitmproxy/mitmproxy/commit/b0b3b19ad644afeb353cf6e02bd4aac61f2774c8
`content_view_lines_cutoff` is only for mitmproxy ui, I guess we need to introduce a new option for the dumper and default to `0` (dump everything) I guess?
In either case `70` is currently a magic number. Magic number bad. Make programmer angry.
Docs say "3: 2 + **full response content**, content of WebSocket and TCP messages.". Liars.
I changed my mind, sort of.
`flow_detail = 4` is simply undocumented :thinking: . You can use it ~as a workaround~ :+1:
I've made a PR for the docs and updated this to be a feature request to make the `70` configurable when using flow_detail 3
> `content_view_lines_cutoff` is only for mitmproxy ui, I guess we need to introduce a new option for the dumper and default to `0` (dump everything) I guess?
We should make it an option for all tools then and reuse it in mitmdump. :) | 2024-02-27T09:39:34 |
mitmproxy/mitmproxy | 6,695 | mitmproxy__mitmproxy-6695 | [
"4506"
] | 92c556afbe631f1ff065d8ffc612f8e04ce9f9d8 | diff --git a/mitmproxy/addons/serverplayback.py b/mitmproxy/addons/serverplayback.py
--- a/mitmproxy/addons/serverplayback.py
+++ b/mitmproxy/addons/serverplayback.py
@@ -16,6 +16,15 @@
logger = logging.getLogger(__name__)
+HASH_OPTIONS = [
+ "server_replay_ignore_content",
+ "server_replay_ignore_host",
+ "server_replay_ignore_params",
+ "server_replay_ignore_payload_params",
+ "server_replay_ignore_port",
+ "server_replay_use_headers",
+]
+
class ServerPlayback:
flowmap: dict[Hashable, list[http.HTTPFlow]]
@@ -255,6 +264,16 @@ def configure(self, updated):
except exceptions.FlowReadException as e:
raise exceptions.OptionsError(str(e))
self.load_flows(flows)
+ if any(option in updated for option in HASH_OPTIONS):
+ self.recompute_hashes()
+
+ def recompute_hashes(self) -> None:
+ """
+ Rebuild flowmap if the hashing method has changed during execution,
+ see https://github.com/mitmproxy/mitmproxy/issues/4506
+ """
+ flows = [flow for lst in self.flowmap.values() for flow in lst]
+ self.load_flows(flows)
def request(self, f: http.HTTPFlow) -> None:
if self.flowmap:
| 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
@@ -325,6 +325,24 @@ def multipart_setter(r, **kwargs):
thash(r, r2, multipart_setter)
+def test_runtime_modify_params():
+ s = serverplayback.ServerPlayback()
+ with taddons.context(s) as tctx:
+ r = tflow.tflow(resp=True)
+ r.request.path = "/test?param1=1"
+ r2 = tflow.tflow(resp=True)
+ r2.request.path = "/test"
+
+ s.load_flows([r])
+ hash = next(iter(s.flowmap.keys()))
+
+ tctx.configure(s, server_replay_ignore_params=["param1"])
+ hash_mod = next(iter(s.flowmap.keys()))
+
+ assert hash != hash_mod
+ assert hash_mod == s._hash(r2)
+
+
def test_server_playback_full():
s = serverplayback.ServerPlayback()
with taddons.context(s) as tctx:
| Unable to set `server_replay_ignore_params` in the UI
#### Value of server_replay_ignore_params is ignored when set in the UI or through command line
#### Steps to reproduce the behavior:
1. Prepare a mock endpoint that works with 5 s delay. In this example I will use a configured mock https://hello.free.beeceptor.com/delay
2. Prepare a recording for the endpoint that contains calls to the endpoint with a parameter `param` (any value) and save it to `my.flow`.
3. Launch the software in the reverse proxy mode, using any of following:
a. `mitmweb --mode reverse:https://hello.free.beeceptor.com --server-replay my.flow --server-replay-nopop --web-port 8888`
b. `mitmproxy --mode reverse:https://hello.free.beeceptor.com --server-replay my_flow --server-replay-nopop`
4. In the UI:
a. Go to Options, Edit Options, set `server_replay_ignore_params` to `param` and close Options.
b. Press Shift-O for Options, scroll to `server_replay_ignore_params`, press `a`, enter `param`, press `Esc`, `q`, `q`.
5. Issue some requests through the proxy with value of `param` not existing in the recording. E.g.
`curl 'http://localhost:8080/delay?param=value5'`
**EDIT**: corrected repro steps for TUI.
#### Problem
The setting has no effect, you will see 5 s delay in the response.
#### System Information
Mitmproxy: 6.0.2
Python: 3.9.2
OpenSSL: OpenSSL 1.1.1i 8 Dec 2020
Platform: macOS-10.15.7-x86_64-i386-64bit
| Thanks! The problem here ist that we compute a hash for each flow when server replay is started, which we then later use to serve that flow:
https://github.com/mitmproxy/mitmproxy/blob/0650f132e9526a6ac881c2fb0cb3f53fba19ed1e/mitmproxy/addons/serverplayback.py#L114-L161
We need to rerun that function and recompute all hashes when one of the options affecting it changes. PRs welcome! 😃
Some notes that I found while testing this issue:
1. This issue only applies when `server_replay_ignore_params` is set through the UI after startup. It works as intended when the option is set before startup
i.e `mitmproxy --mode reverse:https://test-mitm.free.beeceptor.com --server-replay ~/my.flow --server-replay-reuse --set server_replay_ignore_params="param"` works as intended and ignores param while trying to match requests
2. If we set the option through the UI after startup, setting `server_replay_ignore_param` to `param=value` would match requests when the parameter for the request is `param=value` and return the matching response from the capture but wouldn't match `param=value5` i.e the entire `key=value` is matched when the option is set from the UI
I'll try to send a fix for this | 2024-02-28T16:29:20 |
mitmproxy/mitmproxy | 6,718 | mitmproxy__mitmproxy-6718 | [
"6717"
] | b4f49d018697e6349ad7b86c58aadc42f77d31b7 | diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py
--- a/mitmproxy/certs.py
+++ b/mitmproxy/certs.py
@@ -100,15 +100,12 @@ def issuer(self) -> list[tuple[str, str]]:
@property
def notbefore(self) -> datetime.datetime:
- # TODO: Use self._cert.not_valid_before_utc once cryptography 42 hits.
- # x509.Certificate.not_valid_before is a naive datetime in UTC
- return self._cert.not_valid_before.replace(tzinfo=datetime.timezone.utc)
+ # type definitions haven't caught up with new API yet.
+ return self._cert.not_valid_before_utc # type: ignore
@property
def notafter(self) -> datetime.datetime:
- # TODO: Use self._cert.not_valid_after_utc once cryptography 42 hits.
- # x509.Certificate.not_valid_after is a naive datetime in UTC
- return self._cert.not_valid_after.replace(tzinfo=datetime.timezone.utc)
+ return self._cert.not_valid_after_utc # type: ignore
def has_expired(self) -> bool:
if sys.version_info < (3, 11): # pragma: no cover
| Fresh installed mitmproxy 10.2.3 gives a warning from cryptography 42.0.x on startup
#### Problem Description
Fresh installed mitmproxy 10.2.3 gives a warning from cryptography 42.0.x on startup:
`.../pipx/venvs/mitmproxy/lib/python3.12/site-packages/mitmproxy/certs.py:111: CryptographyDeprecationWarning: Properties that return a naïve datetime object have been deprecated. Please switch to not_valid_after_utc.`
` return self._cert.not_valid_after.replace(tzinfo=datetime.timezone.utc)`
May not be a big problem, but feel anxious.
#### Steps to reproduce the behavior:
1. pipx uninstall mitmproxy
2. pipx install mitmproxy
3. run mitmproxy or mitmdump or mitmweb
#### System Information
Mitmproxy: 10.2.3
Python: 3.12.2
OpenSSL: OpenSSL 3.2.1 30 Jan 2024
Platform: macOS-10.13.6-x86_64-i386-64bit
cryptography: 42.0.5
| 2024-03-07T15:32:43 |
||
mitmproxy/mitmproxy | 6,719 | mitmproxy__mitmproxy-6719 | [
"6716"
] | 9acf06427a5c6b790cfba54528adb239c3653d37 | diff --git a/mitmproxy/addons/errorcheck.py b/mitmproxy/addons/errorcheck.py
--- a/mitmproxy/addons/errorcheck.py
+++ b/mitmproxy/addons/errorcheck.py
@@ -3,6 +3,8 @@
import sys
from mitmproxy import log
+from mitmproxy.contrib import click as miniclick
+from mitmproxy.utils import vt_codes
class ErrorCheck:
@@ -29,8 +31,13 @@ async def shutdown_if_errored(self):
if self.logger.has_errored:
plural = "s" if len(self.logger.has_errored) > 1 else ""
if self.repeat_errors_on_stderr:
- msg = "\n".join(self.logger.format(r) for r in self.logger.has_errored)
- print(f"Error{plural} logged during startup:\n{msg}", file=sys.stderr)
+ message = f"Error{plural} logged during startup:"
+ if vt_codes.ensure_supported(sys.stderr): # pragma: no cover
+ message = miniclick.style(message, fg="red")
+ details = "\n".join(
+ self.logger.format(r) for r in self.logger.has_errored
+ )
+ print(f"{message}\n{details}", file=sys.stderr)
else:
print(
f"Error{plural} logged during startup, exiting...", file=sys.stderr
diff --git a/mitmproxy/master.py b/mitmproxy/master.py
--- a/mitmproxy/master.py
+++ b/mitmproxy/master.py
@@ -58,6 +58,7 @@ async def run(self) -> None:
):
self.should_exit.clear()
+ # Can we exit before even bringing up servers?
if ec := self.addons.get("errorcheck"):
await ec.shutdown_if_errored()
if ps := self.addons.get("proxyserver"):
@@ -69,14 +70,23 @@ async def run(self) -> None:
],
return_when=asyncio.FIRST_COMPLETED,
)
- await self.running()
- if ec := self.addons.get("errorcheck"):
- await ec.shutdown_if_errored()
- ec.finish()
+ if self.should_exit.is_set():
+ return
+ # Did bringing up servers fail?
+ if ec := self.addons.get("errorcheck"):
+ await ec.shutdown_if_errored()
+
try:
+ await self.running()
+ # Any errors in the final part of startup?
+ if ec := self.addons.get("errorcheck"):
+ await ec.shutdown_if_errored()
+ ec.finish()
+
await self.should_exit.wait()
finally:
- # .wait might be cancelled (e.g. by sys.exit)
+ # if running() was called, we also always want to call done().
+ # .wait might be cancelled (e.g. by sys.exit), so this needs to be in a finally block.
await self.done()
def shutdown(self):
| diff --git a/test/mitmproxy/addons/test_errorcheck.py b/test/mitmproxy/addons/test_errorcheck.py
--- a/test/mitmproxy/addons/test_errorcheck.py
+++ b/test/mitmproxy/addons/test_errorcheck.py
@@ -6,10 +6,11 @@
from mitmproxy.tools import main
-def test_errorcheck(tdata, capsys):
[email protected]("run_main", [main.mitmdump, main.mitmproxy])
+def test_errorcheck(tdata, capsys, run_main):
"""Integration test: Make sure that we catch errors on startup an exit."""
with pytest.raises(SystemExit):
- main.mitmdump(
+ run_main(
[
"-n",
"-s",
| The mitmproxy program failed to start because the default port 8080 was occupied.
#### Problem Description
Because the default port 8080 is occupied, the mitmproxy program fails to start, and there is no output reason for the failure.
#### Steps to reproduce the behavior:
1. Listen on port 8080 using the nc command in a terminal window.
2. Start the mitmproxy program in another terminal window.
3. The mitmproxy program failed to start, and there was no output reason for the failure, and the normal terminal configuration was not restored.

#### System Information
Mitmproxy: 10.2.3 binary
Python: 3.12.2
OpenSSL: OpenSSL 3.2.1 30 Jan 2024
Platform: macOS-14.2.1-arm64-arm-64bit
| That's bad, thanks. Possibly refs https://github.com/mitmproxy/mitmproxy/issues/6707
bisected to 6e38a56f4c399551c3fe3d399bddfa8083ccd0f1 | 2024-03-07T17:40:33 |
mitmproxy/mitmproxy | 6,749 | mitmproxy__mitmproxy-6749 | [
"6745"
] | 0d68e193b135d08b5f8fb329369811c190517fd0 | diff --git a/mitmproxy/proxy/server.py b/mitmproxy/proxy/server.py
--- a/mitmproxy/proxy/server.py
+++ b/mitmproxy/proxy/server.py
@@ -144,13 +144,13 @@ async def handle_client(self) -> None:
assert writer
writer.close()
else:
+ self.server_event(events.Start())
handler = asyncio_utils.create_task(
self.handle_connection(self.client),
name=f"client connection handler",
client=self.client.peername,
)
self.transports[self.client].handler = handler
- self.server_event(events.Start())
await asyncio.wait([handler])
if not handler.cancelled() and (e := handler.exception()):
self.log(
@@ -249,20 +249,14 @@ async def open_connection(self, command: commands.OpenConnection) -> None:
await self.handle_hook(server_hooks.ServerConnectedHook(hook_data))
self.server_event(events.OpenConnectionCompleted(command, None))
- # during connection opening, this function is the designated handler that can be cancelled.
- # once we have a connection, we do want the teardown here to happen in any case, so we
- # reassign the handler to .handle_connection and then clean up here once that is done.
- new_handler = asyncio_utils.create_task(
- self.handle_connection(command.connection),
- name=f"server connection handler for {addr}",
- client=self.client.peername,
- )
- self.transports[command.connection].handler = new_handler
- await asyncio.wait([new_handler])
-
- self.log(f"server disconnect {addr}")
- command.connection.timestamp_end = time.time()
- await self.handle_hook(server_hooks.ServerDisconnectedHook(hook_data))
+ try:
+ await self.handle_connection(command.connection)
+ finally:
+ self.log(f"server disconnect {addr}")
+ command.connection.timestamp_end = time.time()
+ await self.handle_hook(
+ server_hooks.ServerDisconnectedHook(hook_data)
+ )
async def wakeup(self, request: commands.RequestWakeup) -> None:
await asyncio.sleep(request.delay)
@@ -383,7 +377,7 @@ def server_event(self, event: events.Event) -> None:
assert command.connection not in self.transports
handler = asyncio_utils.create_task(
self.open_connection(command),
- name=f"server connection manager {command.connection.address}",
+ name=f"server connection handler {command.connection.address}",
client=self.client.peername,
)
self.transports[command.connection] = ConnectionIO(handler=handler)
| Async `client_connected` hook is broken in 10.2.4
#### Problem Description
I finally got around upgrading to mitmproxy 10 and things didn't work at all. I was able to track it down to the async `client_connected` hook not working. It does work in 10.0.0 and broken in 10.2.4. Not sure about other hooks, this one starts the entire chain and hence that's where all connections end.
#### Steps to reproduce the behavior:
addon.py
```py
import asyncio
async def client_connected(client):
print("client_connected...")
await asyncio.sleep(1)
print("...client_connected")
```
1. `mitmdump --scripts addon.py`
2. `curl --insecure --proxy localhost:8080 https://example.com/`
Mitmproxy 9.0.1 output:
```
[10:02:00.891] Loading script addon.py
[10:02:00.892] HTTP(S) proxy listening at *:8080.
[10:02:03.639][[::1]:37674] client connect
client_connected...
...client_connected
[10:02:04.746][[::1]:37674] server connect example.com:443 ([2606:2800:220:1:248:1893:25c8:1946]:443)
[::1]:37674: GET https://example.com/ HTTP/2.0
<< HTTP/2.0 200 OK 1.2k
[10:02:05.091][[::1]:37674] client disconnect
[10:02:05.092][[::1]:37674] server disconnect example.com:443 ([2606:2800:220:1:248:1893:25c8:1946]:443)
```
Mitmproxy 10.0.0 output:
```
[10:06:17.770] Loading script addon.py
[10:06:17.771] HTTP(S) proxy listening at *:8080.
[10:06:19.790][[::1]:33394] client connect
client_connected...
...client_connected
[10:06:20.898][[::1]:33394] server connect example.com:443 ([2606:2800:220:1:248:1893:25c8:1946]:443)
[::1]:33394: GET https://example.com/ HTTP/2.0
<< HTTP/2.0 200 OK 1.2k
[10:06:21.241][[::1]:33394] client disconnect
[10:06:21.241][[::1]:33394] server disconnect example.com:443 ([2606:2800:220:1:248:1893:25c8:1946]:443)
```
Mitmproxy 10.2.4 output:
```
[10:03:04.389] Loading script addon.py
[10:03:04.389] HTTP(S) proxy listening at *:8080.
[10:03:07.451][[::1]:35406] client connect
client_connected...
...client_connected
[10:03:08.452][[::1]:35406] mitmproxy has crashed!
Traceback (most recent call last):
File "mitmproxy/proxy/server.py", line 381, in server_event
File "mitmproxy/proxy/layer.py", line 148, in handle_event
File "mitmproxy/proxy/utils.py", line 27, in _check_event_type
AssertionError: Unexpected event type at HttpProxy._handle_event: Expected Start, got DataReceived(client, b'CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\nUser-Agent: curl/8.2.1\r\nProxy-Connection: Keep-Alive\r\n\r\n').
```
#### System Information
```
Mitmproxy: 10.2.4 binary
Python: 3.12.2
OpenSSL: OpenSSL 3.2.1 30 Jan 2024
Platform: Linux-6.5.0-25-generic-x86_64-with-glibc2.38
```
| Broke with `>=10.2.0`
Thanks for the super nice report.
Bisected to 6e38a56f4c399551c3fe3d399bddfa8083ccd0f1 - this is very likely caused by eager task execution as well.
The problem is here:
https://github.com/mitmproxy/mitmproxy/blob/13f42105fd29c0a5dc1889803bac2cc1a460d63d/mitmproxy/proxy/server.py#L147-L153
The handler is now processing events before we reach `server_event(events.Start())`. We probably shouldn't just reorder those statements as this would cause `.handler` to be unset when `server_event` is called initially. We should figure out if we can explicitly spawn tasks lazily here. :) | 2024-03-20T22:06:53 |
|
mitmproxy/mitmproxy | 6,790 | mitmproxy__mitmproxy-6790 | [
"6789"
] | 1b44691d3345604f347ef2b0897914e932528a44 | diff --git a/mitmproxy/certs.py b/mitmproxy/certs.py
--- a/mitmproxy/certs.py
+++ b/mitmproxy/certs.py
@@ -100,16 +100,23 @@ def issuer(self) -> list[tuple[str, str]]:
@property
def notbefore(self) -> datetime.datetime:
- # type definitions haven't caught up with new API yet.
- return self._cert.not_valid_before_utc # type: ignore
+ try:
+ # type definitions haven't caught up with new API yet.
+ return self._cert.not_valid_before_utc # type: ignore
+ except AttributeError: # pragma: no cover
+ # cryptography < 42.0
+ return self._cert.not_valid_before.replace(tzinfo=datetime.timezone.utc)
@property
def notafter(self) -> datetime.datetime:
- return self._cert.not_valid_after_utc # type: ignore
+ try:
+ return self._cert.not_valid_after_utc # type: ignore
+ except AttributeError: # pragma: no cover
+ return self._cert.not_valid_after.replace(tzinfo=datetime.timezone.utc)
def has_expired(self) -> bool:
if sys.version_info < (3, 11): # pragma: no cover
- return datetime.datetime.utcnow() > self._cert.not_valid_after
+ return datetime.datetime.now(datetime.timezone.utc) > self.notafter
return datetime.datetime.now(datetime.UTC) > self.notafter
@property
| Fix CryptographyDeprecationWarnings
When Cryptography>=42.0, CryptographyDeprecationWarnings will be displayed.
#### Description
<!-- describe your changes here -->
#### Checklist
- [x] I have updated tests where applicable.
- [x] I have added an entry to the CHANGELOG.
| 2024-04-09T07:57:02 |
||
mitmproxy/mitmproxy | 6,796 | mitmproxy__mitmproxy-6796 | [
"6729"
] | 61b094ac36ecde0bfef825b1763a1deec15621ad | diff --git a/mitmproxy/addons/tlsconfig.py b/mitmproxy/addons/tlsconfig.py
--- a/mitmproxy/addons/tlsconfig.py
+++ b/mitmproxy/addons/tlsconfig.py
@@ -525,6 +525,6 @@ def _ip_or_dns_name(val: str) -> x509.GeneralName:
try:
ip = ipaddress.ip_address(val)
except ValueError:
- return x509.DNSName(val)
+ return x509.DNSName(val.encode("idna").decode())
else:
return x509.IPAddress(ip)
| diff --git a/test/mitmproxy/addons/test_tlsconfig.py b/test/mitmproxy/addons/test_tlsconfig.py
--- a/test/mitmproxy/addons/test_tlsconfig.py
+++ b/test/mitmproxy/addons/test_tlsconfig.py
@@ -138,12 +138,12 @@ def test_get_cert(self, tdata):
)
# And now we also incorporate SNI.
- ctx.client.sni = "sni.example"
+ ctx.client.sni = "🌈.sni.example"
entry = ta.get_cert(ctx)
assert entry.cert.altnames == x509.GeneralNames(
[
x509.DNSName("example.mitmproxy.org"),
- x509.DNSName("sni.example"),
+ x509.DNSName("xn--og8h.sni.example"),
x509.DNSName("server-address.example"),
]
)
| Failed to proxy HTTPS request to unicode domains
#### Problem Description
Just like issue https://github.com/mitmproxy/mitmproxy/issues/6381.
#### Steps to reproduce the behavior:
1. start mitmproxy: `mitmproxy -p 8080`
2. browse url with proxy setup, for example: `https://tt.广西阀门.net`
and then mitmproxy throws following exception:
```
Addon error: DNSName values should be passed as an A-label string. This means unicode characters should be encoded via a library like idna.
Traceback (most recent call last):
File "/home/pan/.local/lib/python3.10/site-packages/mitmproxy/addons/tlsconfig.py", line 526, in _ip_or_dns_name
ip = ipaddress.ip_address(val)
File "/usr/lib/python3.10/ipaddress.py", line 54, in ip_address
raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 address')
ValueError: 'tt.广西阀门.net' does not appear to be an IPv4 or IPv6 address
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pan/.local/lib/python3.10/site-packages/cryptography/x509/general_name.py", line 85, in __init__
value.encode("ascii")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-6: ordinal not in range(128)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pan/.local/lib/python3.10/site-packages/mitmproxy/addons/tlsconfig.py", line 178, in tls_start_client
entry = self.get_cert(tls_start.context)
File "/home/pan/.local/lib/python3.10/site-packages/mitmproxy/addons/tlsconfig.py", line 512, in get_cert
altnames.append(_ip_or_dns_name(conn_context.server.address[0]))
File "/home/pan/.local/lib/python3.10/site-packages/mitmproxy/addons/tlsconfig.py", line 528, in _ip_or_dns_name
return x509.DNSName(val)
File "/home/pan/.local/lib/python3.10/site-packages/cryptography/x509/general_name.py", line 87, in __init__
raise ValueError(
ValueError: DNSName values should be passed as an A-label string. This means unicode characters should be encoded via a library like idna.
[16:31:32.448][127.0.0.1:53048] No TLS context was provided, failing connection.
```
#### System Information
```sh
$ mitmproxy --version
Mitmproxy: 10.2.4
Python: 3.10.12
OpenSSL: OpenSSL 3.2.1 30 Jan 2024
Platform: Linux-6.5.0-21-generic-x86_64-with-glibc2.35
```
Browser:
```
Google Chrome 122.0.6261.94 (Official Build) (64-bit)
Revision 880dbf29479c6152d5e4f08dfd3a96b30f919e56-refs/branch-heads/6261@{#960}
OS Linux
JavaScript V8 12.2.281.19
User Agent Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
Command Line /usr/bin/google-chrome-stable --flag-switches-begin --flag-switches-end --desktop-startup-id=gnome-shell/Google Chrome/2430-1-PC_TIME219086
```
| 2024-04-12T14:35:03 |
|
mitmproxy/mitmproxy | 6,819 | mitmproxy__mitmproxy-6819 | [
"6818"
] | b2298d7e99ca7b7269b2163868699d2a5af9917d | diff --git a/mitmproxy/addons/readfile.py b/mitmproxy/addons/readfile.py
--- a/mitmproxy/addons/readfile.py
+++ b/mitmproxy/addons/readfile.py
@@ -71,8 +71,6 @@ async def doread(self, rfile: str) -> None:
await self.load_flows_from_path(rfile)
except exceptions.FlowReadException as e:
logger.exception(f"Failed to read {ctx.options.rfile}: {e}")
- finally:
- self._read_task = None
def running(self):
if ctx.options.rfile:
@@ -80,7 +78,7 @@ def running(self):
@command.command("readfile.reading")
def reading(self) -> bool:
- return bool(self._read_task)
+ return bool(self._read_task and not self._read_task.done())
class ReadFileStdin(ReadFile):
| 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
@@ -54,13 +54,21 @@ async def test_read(self, tmpdir, data, corrupt_data, caplog_async):
tf = tmpdir.join("tfile")
- with mock.patch("mitmproxy.master.Master.load_flow") as mck:
- tf.write(data.getvalue())
- tctx.configure(rf, rfile=str(tf), readfile_filter=".*")
- mck.assert_not_awaited()
- rf.running()
+ load_called = asyncio.Event()
+
+ async def load_flow(*_, **__):
+ load_called.set()
+
+ tctx.master.load_flow = load_flow
+
+ tf.write(data.getvalue())
+ tctx.configure(rf, rfile=str(tf), readfile_filter=".*")
+ assert not load_called.is_set()
+ rf.running()
+ await load_called.wait()
+
+ while rf.reading():
await asyncio.sleep(0)
- mck.assert_awaited()
tf.write(corrupt_data.getvalue())
tctx.configure(rf, rfile=str(tf))
| Mitmdump does not exit
#### Problem Description
Mitmdump does not exit automatically when executing:
`mitmdump -nr infile -w outfile
`
Until version 10.0.0 it was working properly and when running mitmdump with "-n" the process finished automatically once the outfile was written.
#### Steps to reproduce the behavior:
1. Generate a mitm file
2. Execute mitmdump -nr infile -w outfile
#### System Information
Mitmproxy: 10.3.0 binary
Python: 3.12.3
OpenSSL: OpenSSL 3.2.1 30 Jan 2024
Platform: Linux-6.5.0-27-generic-x86_64-with-glibc2.35
| Thanks for the report. Bisected to 6e38a56f4c399551c3fe3d399bddfa8083ccd0f1. | 2024-04-24T11:11:58 |
mitmproxy/mitmproxy | 6,866 | mitmproxy__mitmproxy-6866 | [
"6836"
] | ae56c9e488e435dfc7fcff16e43b4f8c6399871a | diff --git a/mitmproxy/addons/proxyauth.py b/mitmproxy/addons/proxyauth.py
--- a/mitmproxy/addons/proxyauth.py
+++ b/mitmproxy/addons/proxyauth.py
@@ -76,6 +76,8 @@ def requestheaders(self, f: http.HTTPFlow) -> None:
# Is this connection authenticated by a previous HTTP CONNECT?
if f.client_conn in self.authenticated:
f.metadata["proxyauth"] = self.authenticated[f.client_conn]
+ elif f.is_replay:
+ pass
else:
self.authenticate_http(f)
| diff --git a/test/mitmproxy/addons/test_proxyauth.py b/test/mitmproxy/addons/test_proxyauth.py
--- a/test/mitmproxy/addons/test_proxyauth.py
+++ b/test/mitmproxy/addons/test_proxyauth.py
@@ -239,6 +239,11 @@ def test_handlers(self):
assert not f2.response
assert f2.metadata["proxyauth"] == ("test", "test")
+ f3 = tflow.tflow()
+ f3.is_replay = True
+ up.requestheaders(f3)
+ assert not f2.response
+
@pytest.mark.parametrize(
"spec",
| httpauth is not attached to replay request
#### Problem Description
I set mitmproxy to run in reverse mode as a proxy to real server, and then protect mitmproxy with a pair of user:pass in the proxyauth option. A regular request would go through, but a reply of that same request would return 401 Unauthorized
#### Steps to reproduce the behavior:
1. turn on reverse mode in mitmweb
2. set basic auth in proxyauth in 'username:pass' format
3. initiate a success request
4. replay the request
#### System Information
Mitmproxy: 10.1.5
Python: 3.11.6
OpenSSL: OpenSSL 3.1.4 24 Oct 2023
Platform: Linux-4.14.276-211.499.amzn2.x86_64-x86_64-with-glibc2.31
| 2024-05-22T00:25:29 |
|
vaexio/vaex | 121 | vaexio__vaex-121 | [
"113"
] | 79276745f0ab0b4fbc470bd367a7018f57ef2256 | diff --git a/packages/vaex-core/vaex/dataset.py b/packages/vaex-core/vaex/dataset.py
--- a/packages/vaex-core/vaex/dataset.py
+++ b/packages/vaex-core/vaex/dataset.py
@@ -1047,10 +1047,17 @@ def selection_from_dict(values):
def fillna(ar, value, fill_nan=True, fill_masked=True):
- '''Returns an array where missing values are replaced by value
+ '''Returns an array where missing values are replaced by value.
+ If the dtype is object, nan values and 'nan' string values
+ are replaced by value when fill_nan==True.
'''
- if ar.dtype.kind == 'f' and fill_nan:
+ if ar.dtype.kind in 'O' and fill_nan:
+ strings = ar.astype(str)
+ mask = strings == 'nan'
+ ar = ar.copy()
+ ar[mask] = value
+ elif ar.dtype.kind in 'f' and fill_nan:
mask = np.isnan(ar)
if np.any(mask):
ar = ar.copy()
@@ -4804,6 +4811,11 @@ def __delitem__(self, item):
raise KeyError('no such column or virtual_columns named %r' % name)
def drop(self, columns, inplace=False):
+ """Drop columns (or single column)
+
+ :param columns: list of columns or single column name
+ """
+ columns = _ensure_list(columns)
ds = self if inplace else self.copy()
for column in columns:
del ds[column]
@@ -4942,7 +4954,7 @@ def myrepr(k):
return str(k)
else:
return repr(k)
- arg_string = ", ".join([myrepr(k) for k in args] + ['{}={}'.format(name, value) for name, value in kwargs.items()])
+ arg_string = ", ".join([myrepr(k) for k in args] + ['{}={}'.format(name, myrepr(value)) for name, value in kwargs.items()])
expression = "{}({})".format(local_name, arg_string)
return vaex.expression.Expression(self, expression)
return wrap
diff --git a/packages/vaex-core/vaex/expression.py b/packages/vaex-core/vaex/expression.py
--- a/packages/vaex-core/vaex/expression.py
+++ b/packages/vaex-core/vaex/expression.py
@@ -276,8 +276,11 @@ def max(self, binby=[], limits=None, shape=default_shape, selection=False, delay
def evaluate(self, i1=None, i2=None, out=None, selection=None):
return self.ds.evaluate(self, i1, i2, out=out, selection=selection)
- # def fillna(self, value, fill_nan=True, fill_masked=True):
- # return self.ds.func.fillna(self, value, fill_nan=fill_nan, fill_masked=fill_masked)
+ # TODO: it is not so elegant we need to have a custom version of this
+ # it now also misses the docstring, reconsider how the the meta class auto
+ # adds this method
+ def fillna(self, value, fill_nan=True, fill_masked=True):
+ return self.ds.func.fillna(self, value=value, fill_nan=fill_nan, fill_masked=fill_masked)
def clip(self, lower=None, upper=None):
return self.ds.func.clip(self, lower, upper)
| diff --git a/tests/common.py b/tests/common.py
--- a/tests/common.py
+++ b/tests/common.py
@@ -37,8 +37,8 @@ def server(webserver):
server.close()
@pytest.fixture()
-def ds_remote(webserver, server):
- ds = ds_trimmed()
+def ds_remote(webserver, server, ds_trimmed):
+ ds = ds_trimmed
ds.name = 'ds_trimmed'
webserver.set_datasets([ds])
return server.datasets(as_dict=True)['ds_trimmed']
@@ -93,7 +93,7 @@ def create_base_ds():
dataset.add_column("x", x)
dataset.add_column("y", y)
# m = x.copy()
- m = m = np.arange(-2, 40, dtype=">f8").reshape((-1,21)).T.copy()[:,0]
+ m = np.arange(-2, 40, dtype=">f8").reshape((-1,21)).T.copy()[:,0]
ma_value = 77777
m[-1+10] = ma_value
m[-1+20] = ma_value
@@ -110,16 +110,22 @@ def create_base_ds():
nm[-1+20] = ma_value
nm = np.ma.array(nm, mask=nm==ma_value)
- mi = mi = np.ma.array(m.data.astype(np.int64), mask=m.data==ma_value, fill_value=88888)
+ mi = np.ma.array(m.data.astype(np.int64), mask=m.data==ma_value, fill_value=88888)
dataset.add_column("m", m)
dataset.add_column('n', n)
dataset.add_column('nm', nm)
dataset.add_column("mi", mi)
dataset.add_column("ints", ints)
-
name = np.array(list(map(lambda x: str(x) + "bla" + ('_' * int(x)), x)), dtype='S') #, dtype=np.string_)
dataset.add_column("name", np.array(name))
+
+ obj_data = np.array(['train', 'false' , True, 1, 30., np.nan, 'something', 'something a bit longer resembling a sentence?!', -10000, 'this should be masked'], dtype='object')
+ obj_mask = np.array([False] * 9 + [True])
+ obj = nm.copy().astype('object')
+ obj[2:12] = np.ma.MaskedArray(data=obj_data, mask=obj_mask, dtype='object')
+ dataset.add_column("obj", obj)
+
return dataset
# dsf = create_filtered()
\ No newline at end of file
diff --git a/tests/export_test.py b/tests/export_test.py
--- a/tests/export_test.py
+++ b/tests/export_test.py
@@ -2,6 +2,8 @@
def test_export(ds_local, tmpdir):
ds = ds_local
+ # TODO: we eventually want to support dtype=object, but not for hdf5
+ ds = ds.drop(ds.obj)
path = str(tmpdir.join('test.hdf5'))
ds.export_hdf5(path)
ds = ds.sample(5)
diff --git a/tests/fillna_test.py b/tests/fillna_test.py
--- a/tests/fillna_test.py
+++ b/tests/fillna_test.py
@@ -1,20 +1,39 @@
from common import *
-import collections
-def test_sample(ds_local):
+
+def test_fillna_column(ds_local):
+ ds = ds_local
+ ds['ok'] = ds['obj'].fillna(value='NA')
+ assert ds.ok.values[5] == 'NA'
+
+
+def test_fillna(ds_local):
ds = ds_local
- x = np.arange(10).tolist()
- dss = ds.sample(frac=1, random_state=42)
- assert dss.x.evaluate().tolist() != x
- assert list(sorted(dss.x.evaluate().tolist())) == x
+ ds_copy = ds.copy()
+
+ ds_string_filled = ds.fillna(value='NA')
+ assert ds_string_filled.obj.values[5] == 'NA'
+
+ ds_filled = ds.fillna(value=0)
+ assert ds_filled.obj.values[5] == 0
+
+ assert ds_filled.to_pandas_df(virtual=True).isna().any().any() == False
+ assert ds_filled.to_pandas_df(virtual=True).isna().any().any() == False
- dss = ds.sample(n=1, random_state=42)
- assert len(dss) == 1
+ ds_filled = ds.fillna(value=10, fill_masked=False)
+ assert ds_filled.n.values[6] == 10.
+ assert ds_filled.nm.values[6] == 10.
- dss = ds.sample(n=100, random_state=42, replace=True)
- assert len(dss) == 100
+ ds_filled = ds.fillna(value=-15, fill_nan=False)
+ assert ds_filled.m.values[7] == -15.
+ assert ds_filled.nm.values[7] == -15.
+ assert ds_filled.mi.values[7] == -15.
+ ds_filled = ds.fillna(value=-11, column_names=['nm', 'mi'])
+ assert ds_filled.to_pandas_df(virtual=True).isna().any().any() == True
+ assert ds_filled.to_pandas_df(column_names=['nm', 'mi']).isna().any().any() == False
- dss = ds.sample(n=100, random_state=42, replace=True, weights='x')
- assert 0 not in dss.x.evaluate().tolist()
- assert 'bla' not in dss.x.evaluate().tolist()
+ state = ds_filled.state_get()
+ ds_copy.state_set(state)
+ np.testing.assert_array_equal(ds_copy['nm'].values, ds_filled['nm'].values)
+ np.testing.assert_array_equal(ds_copy['mi'].values, ds_filled['mi'].values)
| fillna crashes
```
import vaex as vx
ds = vx.open('../datasets/train.csv')
ds['Cabin'] = ds['Cabin'].fillna('NA')
ds['Cabin']
```
Result:
```
<vaex.expression.Expression(expressions='Cabin')> instance at 0x11454beb8 values=[Error evaluating: NameError("name 'NA' is not defined",)]
```
[dataset](https://www.kaggle.com/c/titanic/data)
| It is exposing a bug, you can try this workaround for now:
```
ds = vaex.open('../train.csv')
ds.columns['Cabin'] = ds.columns['Cabin'].astype(str)
ds['Cabin'] = ds.apply(lambda x: 'missing' if x == 'nan' else x, ['Cabin'])
``` | 2018-11-16T11:35:56 |
vaexio/vaex | 154 | vaexio__vaex-154 | [
"93",
"93"
] | 805dfb2fd8d01571ffb2dfbf315ecb538ab269d9 | diff --git a/packages/vaex-core/vaex/dataset_mmap.py b/packages/vaex-core/vaex/dataset_mmap.py
--- a/packages/vaex-core/vaex/dataset_mmap.py
+++ b/packages/vaex-core/vaex/dataset_mmap.py
@@ -20,7 +20,6 @@
import vaex.file
from vaex.expression import Expression
import struct
-import fcntl
logger = logging.getLogger("vaex.file")
@@ -45,6 +44,7 @@
from cachetools import LRUCache
import threading
+ import fcntl
GB = 1024**3
def getsizeof(ar):
return ar.nbytes
| Window OS bug, can't import fcntl
Hi,
**OS: Windows 10.**
I have encountered a bug. When I open a hdf file, using vaex.open('myfile.hdf'), I get the error message below. When I comment out the line 'import fcntl' in dataset_mmap.py , the issue goes away with no noticeable effect. The fcntl module does not work on Windows, see https://stackoverflow.com/questions/1422368/fcntl-substitute-on-windows.
ERROR:MainThread:vaex:error opening 'C:\\myfile.hdf'
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-140-b984d6ab4edc> in <module>()
----> 1 dataVX = vx.open(VXfiles_df.iloc[num]['path'])
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\__init__.py in open(path, convert, shuffle, copy_index, *args, **kwargs)
157 return vaex.distributed.open(path, *args, **kwargs)
158 else:
--> 159 import vaex.file
160 import glob
161 # sort to get predicatable behaviour (useful for testing)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\file\__init__.py in <module>()
3 logger = logging.getLogger("vaex.file")
4
----> 5 import vaex.file.other
6 try:
7 import vaex.hdf5 as hdf5
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\file\other.py in <module>()
24 from vaex.expression import Expression
25
---> 26 from vaex.dataset_mmap import DatasetMemoryMapped
27
28
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\dataset_mmap.py in <module>()
21 from vaex.expression import Expression
22 import struct
---> 23 import fcntl
24
25 logger = logging.getLogger("vaex.file")
ModuleNotFoundError: No module named 'fcntl'
Window OS bug, can't import fcntl
Hi,
**OS: Windows 10.**
I have encountered a bug. When I open a hdf file, using vaex.open('myfile.hdf'), I get the error message below. When I comment out the line 'import fcntl' in dataset_mmap.py , the issue goes away with no noticeable effect. The fcntl module does not work on Windows, see https://stackoverflow.com/questions/1422368/fcntl-substitute-on-windows.
ERROR:MainThread:vaex:error opening 'C:\\myfile.hdf'
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-140-b984d6ab4edc> in <module>()
----> 1 dataVX = vx.open(VXfiles_df.iloc[num]['path'])
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\__init__.py in open(path, convert, shuffle, copy_index, *args, **kwargs)
157 return vaex.distributed.open(path, *args, **kwargs)
158 else:
--> 159 import vaex.file
160 import glob
161 # sort to get predicatable behaviour (useful for testing)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\file\__init__.py in <module>()
3 logger = logging.getLogger("vaex.file")
4
----> 5 import vaex.file.other
6 try:
7 import vaex.hdf5 as hdf5
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\file\other.py in <module>()
24 from vaex.expression import Expression
25
---> 26 from vaex.dataset_mmap import DatasetMemoryMapped
27
28
~\AppData\Local\Continuum\anaconda3\lib\site-packages\vaex\dataset_mmap.py in <module>()
21 from vaex.expression import Expression
22 import struct
---> 23 import fcntl
24
25 logger = logging.getLogger("vaex.file")
ModuleNotFoundError: No module named 'fcntl'
| I have the same problem in Windows10 related to not having fcntl.
The error: ModuleNotFoundError: No module named 'fcntl'
occurs where I have tried using the example dataset with
ds = vaex.example()
or trying with a pandas dataframe loaded previously:
ds = vaex.from_pandas(df)
I would add that I originally tried inside a conda virtualenv, then later reverted to installing via pip and retrying, the error happens in either case.
Thanks for letting me know. This should be fixed actually.
I'd say, try removing all vaex packages, and try with a clean slate, and maybe with a specific version number, like:
```
pip install -c vaex-core=0.6 vaex-hdf5 vaex-viz
```
Let me know if this helps (for conda install the same)
I have the same problem in Windows10 related to not having fcntl.
The error: ModuleNotFoundError: No module named 'fcntl'
occurs where I have tried using the example dataset with
ds = vaex.example()
or trying with a pandas dataframe loaded previously:
ds = vaex.from_pandas(df)
I would add that I originally tried inside a conda virtualenv, then later reverted to installing via pip and retrying, the error happens in either case.
Thanks for letting me know. This should be fixed actually.
I'd say, try removing all vaex packages, and try with a clean slate, and maybe with a specific version number, like:
```
pip install -c vaex-core=0.6 vaex-hdf5 vaex-viz
```
Let me know if this helps (for conda install the same) | 2018-12-14T21:52:43 |
|
vaexio/vaex | 171 | vaexio__vaex-171 | [
"170"
] | d5f09cfd0b72b1da326a9ecb780b2cb6fa9663a1 | diff --git a/packages/vaex-core/vaex/dataset.py b/packages/vaex-core/vaex/dataset.py
--- a/packages/vaex-core/vaex/dataset.py
+++ b/packages/vaex-core/vaex/dataset.py
@@ -1,4 +1,32 @@
from .dataframe import *
+from .dataframe import (
+ # .dataframe imports from .utils
+ _ensure_strings_from_expressions,
+ _ensure_string_from_expression,
+ _ensure_list,
+ _is_limit,
+ _isnumber,
+ _issequence,
+ _is_string,
+ _parse_reduction,
+ _parse_n,
+ _normalize_selection_name,
+ _normalize,
+ _parse_f,
+ _expand,
+ _expand_shape,
+ _expand_limits,
+ _split_and_combine_mask,
+ # dataframe definitions
+ _ColumnConcatenatedLazy,
+ _doc_snippets,
+ _functions_statistics_1d,
+ _hidden,
+ _is_array_type_ok,
+ _is_dtype_ok,
+ _requires
+)
+
# alias kept for backward compatibility
Dataset = DataFrame
DatasetLocal = DataFrameLocal
| plot_widget fails with "AttributeError: module 'vaex.dataset' has no attribute '_ensure_list'"
On a fresh vaex conda install, the following fails
```python
import vaex as vx
import numpy as np
df = vx.from_arrays(
x=np.random.normal(0,0.1,10**6),
y=np.random.lognormal(0,0.1,10**6)
)
df.plot_widget(df.x, df.y) # <-- This fails
```
with this stack trace:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-33-a19d3c9083fd> in <module>
----> 1 df.plot_widget(df.x, df.y)
~/miniconda3/envs/vaex/lib/python3.6/site-packages/vaex/dataframe.py in plot_widget(self, x, y, z, grid, shape, limits, what, figsize, f, figure_key, fig, axes, xlabel, ylabel, title, show, selection, colormap, grid_limits, normalize, grid_before, what_kwargs, type, scales, tool_select, bq_cleanup, backend, **kwargs)
1440 f=f, figure_key=figure_key, fig=fig,
1441 selection=selection, grid_before=grid_before,
-> 1442 grid_limits=grid_limits, normalize=normalize, colormap=colormap, what_kwargs=what_kwargs, **kwargs)
1443 if show:
1444 plot2d.show()
~/miniconda3/envs/vaex/lib/python3.6/site-packages/vaex/jupyter/plot.py in __init__(self, **kwargs)
457
458 def __init__(self, **kwargs):
--> 459 super(Plot2dDefault, self).__init__(**kwargs)
460
461 def colorize(self, grid):
~/miniconda3/envs/vaex/lib/python3.6/site-packages/vaex/jupyter/plot.py in __init__(self, backend, dataset, x, y, z, w, grid, limits, shape, what, f, vshape, selection, grid_limits, normalize, colormap, figure_key, fig, what_kwargs, grid_before, vcount_limits, controls_selection, **kwargs)
146 self.widget_grid_limits = None
147
--> 148 selections = vaex.dataset._ensure_list(self.selection)
149 selections = [_translate_selection(k) for k in selections]
150 selections = [k for k in selections if k]
AttributeError: module 'vaex.dataset' has no attribute '_ensure_list'
```
This is in a clean conda (4.5.12) environment with only `jupyterlab` and `vaex`(and their dependencies) installed from conda-forge:
```shell
$ conda create -n vaex
$ conda activate vaex
$ conda install -c conda-forge jupyterlab vaex
```
For completeness, here's the output of `conda list`:
```
# packages in environment at /Users/teakewerk/miniconda3/envs/vaex:
#
# Name Version Build Channel
aplus 0.11.0 py_1 conda-forge
appnope 0.1.0 py36_1000 conda-forge
asn1crypto 0.24.0 py36_1003 conda-forge
astropy 3.1.1 py36h470a237_0 conda-forge
atomicwrites 1.2.1 py_0 conda-forge
attrs 18.2.0 py_0 conda-forge
backcall 0.1.0 py_0 conda-forge
blas 1.0 mkl defaults
bleach 3.1.0 py_0 conda-forge
bqplot 0.11.3 py36_1000 conda-forge
branca 0.3.1 py_0 conda-forge
ca-certificates 2018.11.29 ha4d7672_0 conda-forge
cachetools 3.0.0 py_0 conda-forge
certifi 2018.11.29 py36_1000 conda-forge
cffi 1.11.5 py36h5e8e0c9_1 conda-forge
chardet 3.0.4 py36_1003 conda-forge
cloudpickle 0.6.1 py_0 conda-forge
cryptography 2.3.1 py36hdffb7b8_0 conda-forge
cryptography-vectors 2.3.1 py36_1000 conda-forge
cycler 0.10.0 py_1 conda-forge
cytoolz 0.9.0.1 py36h470a237_1 conda-forge
dask-core 1.0.0 py_0 conda-forge
decorator 4.3.0 py_0 conda-forge
entrypoints 0.3 py36_1000 conda-forge
freetype 2.9.1 h6debe1e_4 conda-forge
future 0.17.1 py36_1000 conda-forge
h5py 2.9.0 py36he5c79e1_0 conda-forge
hdf5 1.10.4 nompi_h5598ddc_1105 conda-forge
icu 58.2 hfc679d8_0 conda-forge
idna 2.8 py36_1000 conda-forge
imageio 2.4.1 py36_1000 conda-forge
intel-openmp 2019.1 144 defaults
ipydatawidgets 4.0.0 py_0 conda-forge
ipykernel 5.1.0 py36h24bf2e0_1001 conda-forge
ipyleaflet 0.9.2 py36_1001 conda-forge
ipympl 0.2.1 py36_1000 conda-forge
ipyscales 0.3.0 py_0 conda-forge
ipython 7.2.0 py36h24bf2e0_1000 conda-forge
ipython_genutils 0.2.0 py_1 conda-forge
ipyvolume 0.5.1 py36_1001 conda-forge
ipywebrtc 0.4.3 py36_1000 conda-forge
ipywidgets 7.4.2 py_0 conda-forge
jedi 0.13.2 py36_1000 conda-forge
jinja2 2.10 py_1 conda-forge
jpeg 9c h470a237_1 conda-forge
jsonschema 3.0.0a3 py36_1000 conda-forge
jupyter_client 5.2.4 py_0 conda-forge
jupyter_core 4.4.0 py_0 conda-forge
jupyterlab 0.35.4 py36_0 conda-forge
jupyterlab_server 0.2.0 py_0 conda-forge
kapteyn 2.3 py36h18b3941_2 conda-forge
kiwisolver 1.0.1 py36h2d50403_2 conda-forge
libcxx 7.0.0 h2d50403_2 conda-forge
libffi 3.2.1 hfc679d8_5 conda-forge
libgfortran 3.0.1 h93005f0_2 defaults
libpng 1.6.36 ha92aebf_0 conda-forge
libsodium 1.0.16 h470a237_1 conda-forge
libtiff 4.0.10 he6b73bb_1 conda-forge
llvm-meta 7.0.0 0 conda-forge
markupsafe 1.1.0 py36h470a237_0 conda-forge
matplotlib 3.0.2 py36_1 conda-forge
matplotlib-base 3.0.2 py36hb2d221d_1 conda-forge
mistune 0.8.4 py36h470a237_0 conda-forge
mkl 2019.1 144 defaults
mkl_fft 1.0.10 py36_0 conda-forge
mkl_random 1.0.2 py36_0 conda-forge
more-itertools 4.3.0 py36_1000 conda-forge
nbconvert 5.3.1 py_1 conda-forge
nbformat 4.4.0 py_1 conda-forge
ncurses 6.1 hfc679d8_2 conda-forge
networkx 2.2 py_1 conda-forge
notebook 5.7.4 py36_1000 conda-forge
numpy 1.15.4 py36hacdab7b_0 defaults
numpy-base 1.15.4 py36h6575580_0 defaults
olefile 0.46 py_0 conda-forge
openssl 1.0.2p h470a237_2 conda-forge
pandas 0.23.4 py36hf8a1672_0 conda-forge
pandoc 2.5 0 conda-forge
pandocfilters 1.4.2 py_1 conda-forge
parso 0.3.1 py_0 conda-forge
pexpect 4.6.0 py36_1000 conda-forge
pickleshare 0.7.5 py36_1000 conda-forge
pillow 5.4.1 py36hc736899_0 conda-forge
pip 18.1 py36_1000 conda-forge
pluggy 0.8.1 py_0 conda-forge
progressbar2 3.38.0 py_1 conda-forge
prometheus_client 0.5.0 py_0 conda-forge
prompt_toolkit 2.0.7 py_0 conda-forge
psutil 5.4.8 py36h470a237_0 conda-forge
ptyprocess 0.6.0 py36_1000 conda-forge
py 1.7.0 py_0 conda-forge
pycparser 2.19 py_0 conda-forge
pygments 2.3.1 py_0 conda-forge
pyopengl 3.1.1a1 py_1 conda-forge
pyopenssl 18.0.0 py36_1000 conda-forge
pyparsing 2.3.0 py_0 conda-forge
pyqt 5.6.0 py36h8210e8a_8 conda-forge
pyrsistent 0.14.9 py36h470a237_0 conda-forge
pysocks 1.6.8 py36_1002 conda-forge
pytest 4.1.0 py36_1000 conda-forge
pytest-arraydiff 0.3 py_0 conda-forge
pytest-astropy 0.4.0 py_0 conda-forge
pytest-doctestplus 0.1.3 py_0 conda-forge
pytest-openfiles 0.3.1 py_0 conda-forge
pytest-remotedata 0.3.1 py_0 conda-forge
pytest-runner 4.2 py_1 conda-forge
python 3.6.7 h5001a0f_1 conda-forge
python-dateutil 2.7.5 py_0 conda-forge
python-utils 2.3.0 py_1 conda-forge
pythreejs 2.0.2 py36_1000 conda-forge
pytz 2018.9 py_0 conda-forge
pywavelets 1.0.1 py36h7eb728f_0 conda-forge
pyyaml 3.13 py36h470a237_1 conda-forge
pyzmq 17.1.2 py36hae99301_1 conda-forge
qt 5.6.2 h4e759b2_11 conda-forge
readline 7.0 haf1bffa_1 conda-forge
requests 2.21.0 py36_1000 conda-forge
scikit-image 0.14.1 py36hfc679d8_4 conda-forge
scipy 1.1.0 py36h1410ff5_2 defaults
send2trash 1.5.0 py_0 conda-forge
setuptools 40.6.3 py36_0 conda-forge
sip 4.18.1 py36hfc679d8_0 conda-forge
six 1.12.0 py36_1000 conda-forge
sqlite 3.26.0 hb1c47c0_0 conda-forge
tabulate 0.8.2 py_0 conda-forge
terminado 0.8.1 py36_1001 conda-forge
testpath 0.4.2 py36_1000 conda-forge
tk 8.6.9 ha92aebf_0 conda-forge
toolz 0.9.0 py_1 conda-forge
tornado 5.1.1 py36h470a237_0 conda-forge
traitlets 4.3.2 py36_1000 conda-forge
traittypes 0.2.1 py_1 conda-forge
urllib3 1.24.1 py36_1000 conda-forge
vaex 1.0.0b7 py_0 conda-forge
vaex-astro 0.2.0 py36_0 conda-forge
vaex-core 0.6.1 py36hf8a1672_0 conda-forge
vaex-distributed 0.2.0 py_0 conda-forge
vaex-hdf5 0.2.1 py_0 conda-forge
vaex-jupyter 0.2.1 py_0 conda-forge
vaex-server 0.2.1 py_0 conda-forge
vaex-ui 0.2.0 py_0 conda-forge
vaex-viz 0.3.2 py_0 conda-forge
wcwidth 0.1.7 py_1 conda-forge
webencodings 0.5.1 py_1 conda-forge
wheel 0.32.3 py36_0 conda-forge
widgetsnbextension 3.4.2 py36_1000 conda-forge
xarray 0.10.9 py36_1000 conda-forge
xz 5.2.4 h470a237_1 conda-forge
yaml 0.1.7 h470a237_1 conda-forge
zeromq 4.2.5 hfc679d8_6 conda-forge
zlib 1.2.11 h470a237_4 conda-forge
```
| 2019-01-10T13:21:55 |
||
vaexio/vaex | 177 | vaexio__vaex-177 | [
"173"
] | f654e895e48a1c5080ad9f84df9a2c31c7add64a | diff --git a/packages/vaex-ui/vaex/ui/layers.py b/packages/vaex-ui/vaex/ui/layers.py
--- a/packages/vaex-ui/vaex/ui/layers.py
+++ b/packages/vaex-ui/vaex/ui/layers.py
@@ -2737,5 +2737,6 @@ def update(self):
self.flag_needs_update()
self.plot_window.queue_update()
-from vaex.dataset import Dataset, Task
+from vaex.dataset import Dataset
+from vaex.tasks import Task
from vaex.ui.plot_windows import PlotDialog
| ImportError: cannot import name 'Task'
https://github.com/vaexio/vaex/blob/f654e895e48a1c5080ad9f84df9a2c31c7add64a/packages/vaex-ui/vaex/ui/layers.py#L2740
Sorry but this version does not find Task in `vaex.dataset`. Should this be imported from tasks instead?
| 2019-02-04T10:16:29 |
||
vaexio/vaex | 217 | vaexio__vaex-217 | [
"209"
] | 255ccbc192d54c619a273de21a05f919da8ffadf | diff --git a/packages/vaex-core/vaex/formatting.py b/packages/vaex-core/vaex/formatting.py
--- a/packages/vaex-core/vaex/formatting.py
+++ b/packages/vaex-core/vaex/formatting.py
@@ -1,7 +1,7 @@
import numpy as np
import numbers
import six
-import pandas as pd
+import datetime
MAX_LENGTH = 50
@@ -15,9 +15,24 @@ def _format_value(value):
elif isinstance(value, np.ma.core.MaskedConstant):
value = str(value)
if isinstance(value, np.datetime64):
- value = str(pd.to_datetime(value))
+ if np.isnat(value):
+ value = 'NaT'
+ else:
+ value = ' '.join(str(value).split('T'))
if isinstance(value, np.timedelta64):
- value = str(pd.to_timedelta(value))
+ if np.isnat(value):
+ value = 'NaT'
+ else:
+ tmp = datetime.timedelta(seconds=value / np.timedelta64(1, 's'))
+ ms = tmp.microseconds
+ s = np.mod(tmp.seconds, 60)
+ m = np.mod(tmp.seconds//60, 60)
+ h = tmp.seconds // 3600
+ d = tmp.days
+ if ms:
+ value = str('%i days %+02i:%02i:%02i.%i' % (d,h,m,s,ms))
+ else:
+ value = str('%i days %+02i:%02i:%02i' % (d,h,m,s))
elif not isinstance(value, numbers.Number):
value = str(value)
if isinstance(value, float):
| Pandas dependency
We now depends on Pandas:
https://github.com/vaexio/vaex/blob/255ccbc192d54c619a273de21a05f919da8ffadf/packages/vaex-core/vaex/formatting.py
Introduced in https://github.com/vaexio/vaex/pull/192
We should not depend on pandas, it is not a dependency of vaex-core and should not become, we might also grow to large to run on AWS Lambda.
| 2019-04-16T09:18:18 |
||
vaexio/vaex | 225 | vaexio__vaex-225 | [
"222"
] | 52c3c22a9f6aa6ce8ddc636c47cd95c78d990b8e | diff --git a/packages/vaex-core/vaex/dataframe.py b/packages/vaex-core/vaex/dataframe.py
--- a/packages/vaex-core/vaex/dataframe.py
+++ b/packages/vaex-core/vaex/dataframe.py
@@ -4293,6 +4293,12 @@ def __delitem__(self, item):
self.column_names.remove(name)
else:
raise KeyError('no such column or virtual_columns named %r' % name)
+ if hasattr(self, name):
+ try:
+ if isinstance(getattr(self, name), Expression):
+ delattr(self, name)
+ except:
+ pass
@docsubst
def drop(self, columns, inplace=False, check=True):
| diff --git a/tests/drop_test.py b/tests/drop_test.py
--- a/tests/drop_test.py
+++ b/tests/drop_test.py
@@ -29,3 +29,20 @@ def test_drop_depending_filtered(ds_filtered):
assert 'x' not in ds.get_column_names()
assert '__x' in ds.get_column_names(hidden=True)
ds.y.values # make sure we can evaluate y
+
+def test_drop_autocomplete(ds_local):
+ ds = ds_local
+ ds['drop'] = ds.m
+ ds['columns'] = ds.m
+
+ del ds['x']
+ assert not hasattr(ds, 'x')
+
+ ds.drop('y', inplace=True)
+ assert not hasattr(ds, 'y')
+
+ # make sure we can also remove with name issues
+ del ds['drop']
+ assert callable(ds.drop)
+ del ds['columns']
+ assert 'm' in ds.columns
| Deletion of a (virtual) column shows up in autocomplete (jupyter, ipython)
I am not 100% sure if this is the correct way we want to "delete" in-memory columns, in this example:
```
import vaex
ds = vaex.example()
del ds['x']
```
in Jupyter and IPython one still gets `ds.x` to show up via the auto-complete, while of course, the "x" column is no longer accessible.
(Note to anyone reading this: `del ds['x']` does not modify the original hdf5/arrow/csv file on disk. Well not unless one exports the `ds` and overwrites the original file. )
| I wouldn't say in memory, any column. I'll see if I can fix it. | 2019-04-23T13:05:12 |
vaexio/vaex | 280 | vaexio__vaex-280 | [
"279"
] | 76ddb311420a1aaa6b3055e6b34d22718cb1770d | diff --git a/packages/vaex-core/vaex/dataset_mmap.py b/packages/vaex-core/vaex/dataset_mmap.py
--- a/packages/vaex-core/vaex/dataset_mmap.py
+++ b/packages/vaex-core/vaex/dataset_mmap.py
@@ -1,21 +1,12 @@
__author__ = 'maartenbreddels'
import os
import mmap
-import math
-import itertools
-import functools
import collections
import logging
import numpy as np
import numpy.ma
import vaex
-import astropy.table
-import astropy.units
-from vaex.utils import ensure_string
-import astropy.io.fits as fits
-import re
-import six
-from vaex.dataset import DatasetLocal, DatasetArrays
+from vaex.dataset import DatasetLocal
import vaex.dataset
import vaex.file
from vaex.expression import Expression
@@ -26,14 +17,6 @@
dataset_type_map = {}
-# h5py doesn't want to build at readthedocs
-on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
-try:
- import h5py
-except:
- if not on_rtd:
- raise
-
osname = vaex.utils.osname
no_mmap = os.environ.get('VAEX_NO_MMAP', False)
| `from_pandas` missing h5py in vaex-core
Reproduce environment:
```sh
conda create -n vaex_from_pandas_issue vaex-core pandas -c conda-forge
conda activate vaex_from_pandas_issue
```
Trigger problem:
```python
import vaex as vx
import pandas as pd
vx.from_pandas(pd.DataFrame({'x': (1,2,3), 'y': (4,5,6)}))
```
| The fix is probably to add h5py to the conda dependencies for vaex-core.
Thanks for this!
Can you please also provide the error traceback?
```pytb
ERROR:MainThread:vaex:error evaluating: x at rows 0-3
Traceback (most recent call last):
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 3376, in table_part
values[name] = self.evaluate(name, i1=k1, i2=k2)
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 4713, in evaluate
value = scope.evaluate(expression)
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/scopes.py", line 86, in evaluate
result = self[expression]
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/scopes.py", line 111, in __getitem__
if self.df._needs_copy(variable):
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 5032, in _needs_copy
import vaex.file.other
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/file/__init__.py", line 10, in <module>
import vaex.file.other
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/file/other.py", line 26, in <module>
from vaex.dataset_mmap import DatasetMemoryMapped
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataset_mmap.py", line 31, in <module>
import h5py
ModuleNotFoundError: No module named 'h5py'
ERROR:MainThread:vaex:error evaluating: y at rows 0-3
Traceback (most recent call last):
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 3376, in table_part
values[name] = self.evaluate(name, i1=k1, i2=k2)
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 4713, in evaluate
value = scope.evaluate(expression)
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/scopes.py", line 86, in evaluate
result = self[expression]
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/scopes.py", line 111, in __getitem__
if self.df._needs_copy(variable):
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 5032, in _needs_copy
import vaex.file.other
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/file/__init__.py", line 10, in <module>
import vaex.file.other
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/file/other.py", line 26, in <module>
from vaex.dataset_mmap import DatasetMemoryMapped
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataset_mmap.py", line 31, in <module>
import h5py
ModuleNotFoundError: No module named 'h5py'
ERROR:MainThread:vaex:error evaluating: index at rows 0-3
Traceback (most recent call last):
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 3376, in table_part
values[name] = self.evaluate(name, i1=k1, i2=k2)
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 4713, in evaluate
value = scope.evaluate(expression)
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/scopes.py", line 86, in evaluate
result = self[expression]
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/scopes.py", line 111, in __getitem__
if self.df._needs_copy(variable):
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataframe.py", line 5032, in _needs_copy
import vaex.file.other
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/file/__init__.py", line 10, in <module>
import vaex.file.other
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/file/other.py", line 26, in <module>
from vaex.dataset_mmap import DatasetMemoryMapped
File "/Users/pbos/sw/miniconda3/envs/vaex_from_pandas_issue/lib/python3.7/site-packages/vaex/dataset_mmap.py", line 31, in <module>
import h5py
ModuleNotFoundError: No module named 'h5py'
# x y index
0 error error error
1 error error error
2 error error error
```
Thank you!
Maybe also good to add the above to the integration tests :) | 2019-05-31T13:18:38 |
|
vaexio/vaex | 297 | vaexio__vaex-297 | [
"273"
] | dc6eaf3280c2acb6ab9e4eb72e72e28d45930033 | diff --git a/packages/vaex-hdf5/vaex/hdf5/dataset.py b/packages/vaex-hdf5/vaex/hdf5/dataset.py
--- a/packages/vaex-hdf5/vaex/hdf5/dataset.py
+++ b/packages/vaex-hdf5/vaex/hdf5/dataset.py
@@ -224,9 +224,10 @@ def _load_variables(self, h5variables):
def _map_hdf5_array(self, data, mask=None):
offset = data.id.get_offset()
+ if len(data) == 0 and offset is None:
+ offset = 0 # we don't care about the offset for empty arrays
if offset is None: # non contiguous array, chunked arrays etc
# we don't support masked in this case
- raise "try"
column = ColumnNumpyLike(data)
return column
else:
@@ -239,7 +240,7 @@ def _map_hdf5_array(self, data, mask=None):
if dtype == 'utf32':
dtype = np.dtype('U' + str(data.attrs['dlength']))
#self.addColumn(column_name, offset, len(data), dtype=dtype)
- array = self._map_array(data.id.get_offset(), dtype=dtype, length=len(data))
+ array = self._map_array(offset, dtype=dtype, length=len(data))
if mask is not None:
mask_array = self._map_hdf5_array(mask)
return np.ma.array(array, mask=mask_array, shrink=False)
diff --git a/packages/vaex-hdf5/vaex/hdf5/export.py b/packages/vaex-hdf5/vaex/hdf5/export.py
--- a/packages/vaex-hdf5/vaex/hdf5/export.py
+++ b/packages/vaex-hdf5/vaex/hdf5/export.py
@@ -171,7 +171,8 @@ def export_hdf5(dataset, path, column_names=None, byteorder="=", shuffle=False,
indices_shape = (N+1, )
array = h5column_output.require_dataset('data', shape=data_shape, dtype='S1')
- array[0] = array[0] # make sure the array really exists
+ if byte_length > 0:
+ array[0] = array[0] # make sure the array really exists
index_array = h5column_output.require_dataset('indices', shape=indices_shape, dtype=dtype_indices)
index_array[0] = index_array[0] # make sure the array really exists
| diff --git a/tests/export_test.py b/tests/export_test.py
--- a/tests/export_test.py
+++ b/tests/export_test.py
@@ -2,6 +2,16 @@
import os
import tempfile
+
[email protected]("filename", ["test.hdf5", "test.arrow"])
+def test_export_empty_string(tmpdir, filename):
+ path = str(tmpdir.join('test.hdf5'))
+ s = np.array(["", ""])
+ df = vaex.from_arrays(s=s)
+ df.export(path)
+ vaex.open(path)
+
+
def test_export(ds_local, tmpdir):
ds = ds_local
# TODO: we eventually want to support dtype=object, but not for hdf5
| Error when exporting df with a column containing only empty strings.
There is an error appearing when one tries to export a DataFrame that contains a column which has only empty strings.
`df.export_arrow` does not seem affected by this, but opening such a file causes an error.
| Thanks! | 2019-06-13T19:30:01 |
vaexio/vaex | 298 | vaexio__vaex-298 | [
"274"
] | dc6eaf3280c2acb6ab9e4eb72e72e28d45930033 | diff --git a/packages/vaex-core/vaex/dataframe.py b/packages/vaex-core/vaex/dataframe.py
--- a/packages/vaex-core/vaex/dataframe.py
+++ b/packages/vaex-core/vaex/dataframe.py
@@ -4423,6 +4423,9 @@ def __getitem__(self, item):
start, stop, step = item.start, item.stop, item.step
start = start or 0
stop = stop or len(self)
+ if stop < 0:
+ stop = len(self)+stop
+ stop = min(stop, len(self))
assert step in [None, 1]
if self.filtered and start == 0:
mask = self._selection_masks[FILTER_SELECTION_NAME]
| diff --git a/tests/slice_test.py b/tests/slice_test.py
--- a/tests/slice_test.py
+++ b/tests/slice_test.py
@@ -36,3 +36,15 @@ def test_head_with_selection():
df = vaex.example()
df.select(df.x > 0, name='test')
df.head()
+
+
+def test_slice_beyond_end(df):
+ df2 = df[:100]
+ assert df2.x.tolist() == df.x.tolist()
+ assert len(df2) == len(df)
+
+
+def test_slice_negative(df):
+ df2 = df[:-1]
+ assert df2.x.tolist() == df.x.values[:-1].tolist()
+ assert len(df2) == len(df)-1
| Simple issue with DataFrame slicing out-of-bounds case
We have an issue when an out-of-bounds index is specified when slicing a DataFrame. Consider this example:
```
import vaex
df = vaex.from_arrays(x = [0, 1, 2, 3, 4, 5, 6, 7])
```
now
```
df[:3]
# x
0 0
1 1
2 2
```
but when `df[:10]` a `ValueError: array is of length 8, while the length of the DataFrame is 10` is raised.
I would expect the default behaviour to be that the whole DataFrame is printed.
| 2019-06-13T19:41:43 |
|
vaexio/vaex | 299 | vaexio__vaex-299 | [
"221"
] | 4771c562b7bb8b2aaafd0beb1555dad12894aad8 | diff --git a/packages/vaex-core/vaex/dataframe.py b/packages/vaex-core/vaex/dataframe.py
--- a/packages/vaex-core/vaex/dataframe.py
+++ b/packages/vaex-core/vaex/dataframe.py
@@ -646,6 +646,9 @@ def _compute_agg(self, name, expression, binby=[], limits=None, shape=default_sh
if extra_expressions:
extra_expressions = _ensure_strings_from_expressions(extra_expressions)
expression_waslist, [expressions,] = vaex.utils.listify(expression)
+ for expression in expressions:
+ if expression and expression != "*":
+ self.validate_expression(expression)
assert self._aggregator_nest_count == 0, "detected nested aggregator call"
# Instead of 'expression is not None', we would like to have 'not virtual'
# but in agg.py we do some casting, which results in calling .dtype(..) with a non-column
@@ -2849,9 +2852,16 @@ def getitem(df, item):
def validate_expression(self, expression):
"""Validate an expression (may throw Exceptions)"""
# return self.evaluate(expression, 0, 2)
- vars = set(self.get_column_names()) | set(self.variables.keys())
- funcs = set(expression_namespace.keys())
- return vaex.expresso.validate_expression(expression, vars, funcs)
+ if str(expression) in self.virtual_columns:
+ return
+ if self.is_local() and str(expression) in self.columns:
+ return
+ vars = set(self.get_names(hidden=True))
+ funcs = set(expression_namespace.keys()) | set(self.functions.keys())
+ try:
+ return vaex.expresso.validate_expression(expression, vars, funcs)
+ except NameError as e:
+ raise NameError(str(e)) from None
def _block_scope(self, i1, i2):
variables = {key: self.evaluate_variable(key) for key in self.variables.keys()}
@@ -4497,6 +4507,7 @@ def __getitem__(self, item):
item = self._column_aliases[item] # translate the alias name into the real name
# if item in self._virtual_expressions:
# return self._virtual_expressions[item]
+ self.validate_expression(item)
return Expression(self, item) # TODO we'd like to return the same expression if possible
elif isinstance(item, Expression):
expression = item.expression
@@ -4512,6 +4523,8 @@ def __getitem__(self, item):
elif isinstance(item[1], slice):
names = self.get_column_names().__getitem__(item[1])
return df[names]
+ for expression in item:
+ self.validate_expression(expression)
df = self.copy(column_names=item)
return df
elif isinstance(item, slice):
@@ -4722,6 +4735,9 @@ def _create_grid(self, binby, limits, shape, delay=False):
else:
binbys = [binby]
binbys = _ensure_strings_from_expressions(binbys)
+ for expression in binbys:
+ if expression:
+ self.validate_expression(expression)
binners = []
if len(binbys):
limits = _expand_limits(limits, len(binbys))
@@ -4910,6 +4926,7 @@ def copy(self, column_names=None, virtual=True):
depending.update(deps)
else:
# this might be an expression, create a valid name
+ self.validate_expression(name)
expression = name
name = vaex.utils.find_valid_name(name)
# add the expression
diff --git a/packages/vaex-core/vaex/expresso.py b/packages/vaex-core/vaex/expresso.py
--- a/packages/vaex-core/vaex/expresso.py
+++ b/packages/vaex-core/vaex/expresso.py
@@ -10,6 +10,8 @@
import sys
import six
import copy
+import difflib
+
logger = logging.getLogger("expr")
logger.setLevel(logging.ERROR)
@@ -82,11 +84,17 @@ def validate_expression(expr, variable_set, function_set=[], names=None):
elif isinstance(expr, _ast.Name):
validate_id(expr.id)
if expr.id not in variable_set:
- raise NameError("variable %r is not defined (available are: %s)" % (
- expr.id, ", ".join(list(variable_set))))
+ matches = difflib.get_close_matches(expr.id, list(variable_set))
+ msg = "Column or variable %r does not exist." % expr.id
+ if matches:
+ msg += ' Did you mean: ' + " or ".join(map(repr, matches))
+
+ raise NameError(msg)
names.append(expr.id)
elif isinstance(expr, _ast.Num):
pass # numbers are fine
+ elif isinstance(expr, _ast.Str):
+ pass # as well as strings
elif isinstance(expr, _ast.Call):
validate_func(expr.func, function_set)
last_func = expr
| diff --git a/tests/copy_test.py b/tests/copy_test.py
--- a/tests/copy_test.py
+++ b/tests/copy_test.py
@@ -1,4 +1,6 @@
from common import *
+import pytest
+
def test_copy(df):
df = df
@@ -10,4 +12,9 @@ def test_copy(df):
assert 'v' in dfc.get_column_names()
assert 'v' in dfc.virtual_columns
assert 'myvar' in dfc.variables
- dfc.x.values
\ No newline at end of file
+ dfc.x.values
+
+def test_non_existing_column(df_local):
+ df = df_local
+ with pytest.raises(NameError, match='.*Did you.*'):
+ df.copy(column_names=['x', 'x_'])
diff --git a/tests/getattr_test.py b/tests/getattr_test.py
--- a/tests/getattr_test.py
+++ b/tests/getattr_test.py
@@ -92,3 +92,8 @@ def test_access_data_after_virtual_column_creation(ds_local):
ds['virtual'] = ds.x * 2
# it should also work after we added a virtual column
assert ds[['x']].values[:,0].tolist() == ds.x.values.tolist()
+
+def test_non_existing_column(df_local):
+ df = df_local
+ with pytest.raises(NameError, match='.*Did you.*'):
+ df['x_']
| Better handling when a non-existend column is used.
We need a better way to catch an error when a user makes a typo and queries a column that does not exist in a `DataFrame`. For example:
```
import vaex
ds = vaex.example()
ds[['x', 'xy']] # gives a not so friendly error
```
On the other hand:
```
import vaex
ds = vaex.example()
ds['xy'] # gives a helpful error message
```
| 2019-06-14T18:25:41 |
|
vaexio/vaex | 312 | vaexio__vaex-312 | [
"308"
] | 5f449f326e4165344704c0867ddd0a288b9403fd | diff --git a/packages/vaex-core/vaex/agg.py b/packages/vaex-core/vaex/agg.py
--- a/packages/vaex-core/vaex/agg.py
+++ b/packages/vaex-core/vaex/agg.py
@@ -24,7 +24,7 @@ class AggregatorDescriptorBasic(AggregatorDescriptor):
def __init__(self, name, expression, short_name, multi_args=False, agg_args=[]):
self.name = name
self.short_name = short_name
- self.expression = expression
+ self.expression = str(expression)
self.agg_args = agg_args
if not multi_args:
if self.expression == '*':
@@ -66,10 +66,6 @@ def __init__(self, name, expression, short_name):
self.short_name = short_name
self.expression = expression
self.expressions = [self.expression]
- self._add_sub_agg()
-
- def _add_sub_agg(self):
- pass
def pretty_name(self, id=None):
id = id or "_".join(map(str, self.expression))
@@ -80,15 +76,20 @@ class AggregatorDescriptorMean(AggregatorDescriptorMulti):
def __init__(self, name, expression, short_name="mean"):
super(AggregatorDescriptorMean, self).__init__(name, expression, short_name)
- def _add_sub_agg(self):
- self.sum = sum(self.expression)
- self.count = count(self.expression)
-
def add_operations(self, agg_task, **kwargs):
- task_sum = self.sum.add_operations(agg_task, **kwargs)
- task_count = self.count.add_operations(agg_task, **kwargs)
- self.dtype_in = self.sum.dtype_in
- self.dtype_out = self.sum.dtype_out
+ expression = expression_sum = expression = agg_task.df[str(self.expression)]
+ # ints, floats and bools are upcasted
+ if expression_sum.dtype.kind in "buif":
+ expression = expression_sum = expression_sum.astype('float64')
+
+ sum_agg = sum(expression_sum)
+ count_agg = count(expression)
+
+ task_sum = sum_agg.add_operations(agg_task, **kwargs)
+ task_count = count_agg.add_operations(agg_task, **kwargs)
+ self.dtype_in = sum_agg.dtype_in
+ self.dtype_out = sum_agg.dtype_out
+
@vaex.delayed
def finish(sum, count):
dtype = sum.dtype
@@ -101,6 +102,7 @@ def finish(sum, count):
# TODO: not sure why view does not work
mean = mean.astype(dtype)
return mean
+
return finish(task_sum, task_count)
@@ -123,7 +125,6 @@ def add_operations(self, agg_task, **kwargs):
self.dtype_out = sum_.dtype_out
@vaex.delayed
def finish(sum_moment, sum, count):
- # print(self.sum, sum, task_sum)
dtype = sum.dtype
if sum.dtype.kind == 'M':
sum = sum.view('uint64')
@@ -131,7 +132,6 @@ def finish(sum_moment, sum, count):
count = count.view('uint64')
with np.errstate(divide='ignore', invalid='ignore'):
mean = sum / count
- print(sum, sum_moment)
raw_moments2 = sum_moment/count
variance = (raw_moments2 - mean**2) #* count/(count-self.ddof)
if dtype.kind != mean.dtype.kind:
| diff --git a/tests/groupby_test.py b/tests/groupby_test.py
--- a/tests/groupby_test.py
+++ b/tests/groupby_test.py
@@ -128,13 +128,13 @@ def test_groupby_datetime_quarter():
def test_groupby_count():
# ds = ds_local.extract()
- g = np.array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2], dtype='int32')
+ g = np.array([0, 0, 0, 0, 1, 1, 1, 1, 0, 1], dtype='int32')
s = np.array(list(map(str, [0, 0, 0, 0, 1, 1, 1, 1, 2, 2])))
df = vaex.from_arrays(g=g, s=s)
groupby = df.groupby('s')
dfg = groupby.agg({'g': 'mean'}).sort('s')
assert dfg.s.tolist() == ['0', '1', '2']
- assert dfg.g.tolist() == [0, 1, 2]
+ assert dfg.g.tolist() == [0, 1, 0.5]
dfg2 = df.groupby('s', {'g': 'mean'}).sort('s')
assert dfg._equals(dfg2)
| vaex.groupby type casting
In the current implementation of `groupby`, if a column is on of type `int`, calculating the mean will also be of type `int`, which is numerically not accurate. This should probably be cased to `float` somewhere behind the scenes.
| 2019-06-25T17:50:29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.