2018-02-03 20:37:33 +00:00
|
|
|
import typing
|
|
|
|
|
2021-12-20 21:10:06 +00:00
|
|
|
from mitmproxy import http
|
|
|
|
from mitmproxy.connection import Server
|
|
|
|
from mitmproxy.net.server_spec import ServerSpec
|
|
|
|
|
|
|
|
|
2014-11-10 14:51:26 +00:00
|
|
|
# This scripts demonstrates how mitmproxy can switch to a second/different upstream proxy
|
2014-09-07 16:01:30 +00:00
|
|
|
# in upstream proxy mode.
|
|
|
|
#
|
2021-12-20 21:10:06 +00:00
|
|
|
# Usage: mitmdump
|
|
|
|
# -s change_upstream_proxy.py
|
|
|
|
# --mode upstream:http://default-upstream-proxy:8080/
|
|
|
|
# --set connection_strategy=lazy
|
|
|
|
# --set upstream_cert=false
|
2015-08-30 22:14:42 +00:00
|
|
|
#
|
|
|
|
# If you want to change the target server, you should modify flow.request.host and flow.request.port
|
2015-05-30 00:03:28 +00:00
|
|
|
|
|
|
|
|
2018-02-03 20:37:33 +00:00
|
|
|
def proxy_address(flow: http.HTTPFlow) -> typing.Tuple[str, int]:
|
2015-08-30 22:14:42 +00:00
|
|
|
# Poor man's loadbalancing: route every second domain through the alternative proxy.
|
|
|
|
if hash(flow.request.host) % 2 == 1:
|
|
|
|
return ("localhost", 8082)
|
|
|
|
else:
|
|
|
|
return ("localhost", 8081)
|
2014-09-07 16:01:30 +00:00
|
|
|
|
|
|
|
|
2018-02-03 20:37:33 +00:00
|
|
|
def request(flow: http.HTTPFlow) -> None:
|
2015-08-30 22:14:42 +00:00
|
|
|
address = proxy_address(flow)
|
2021-12-20 21:10:06 +00:00
|
|
|
|
|
|
|
is_proxy_change = address != flow.server_conn.via.address
|
|
|
|
server_connection_already_open = flow.server_conn.timestamp_start is not None
|
|
|
|
if is_proxy_change and server_connection_already_open:
|
|
|
|
# server_conn already refers to an existing connection (which cannot be modified),
|
|
|
|
# so we need to replace it with a new server connection object.
|
|
|
|
flow.server_conn = Server(flow.server_conn.address)
|
|
|
|
flow.server_conn.via = ServerSpec("http", address)
|