Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- python/user_packages/Python313/site-packages/mitmproxy/addons/__init__.py +67 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/anticache.py +18 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/anticomp.py +15 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/asgiapp.py +144 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/block.py +48 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/blocklist.py +81 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/browser.py +186 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/clientplayback.py +298 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/command_history.py +96 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/comment.py +19 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/core.py +286 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/cut.py +176 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/disable_h2c.py +42 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/dns_resolver.py +182 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/dumper.py +427 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/errorcheck.py +55 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/eventstore.py +56 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/export.py +232 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/intercept.py +63 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/keepserving.py +54 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/maplocal.py +151 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/mapremote.py +68 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/modifybody.py +86 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/modifyheaders.py +117 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/next_layer.py +474 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/onboarding.py +34 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/proxyauth.py +298 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/proxyserver.py +396 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/readfile.py +98 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/save.py +197 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/savehar.py +312 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/script.py +229 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/server_side_events.py +23 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/serverplayback.py +305 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/stickyauth.py +38 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/stickycookie.py +97 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/strip_dns_https_records.py +37 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/termlog.py +50 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/tlsconfig.py +654 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/update_alt_svc.py +33 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/upstream_auth.py +62 -0
- python/user_packages/Python313/site-packages/mitmproxy/addons/view.py +749 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_api.py +116 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_compat.py +74 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_registry.py +73 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_utils.py +106 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_css.py +76 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_dns.py +53 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_graphql.py +72 -0
- python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_http3.py +153 -0
python/user_packages/Python313/site-packages/mitmproxy/addons/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mitmproxy.addons import anticache
|
| 2 |
+
from mitmproxy.addons import anticomp
|
| 3 |
+
from mitmproxy.addons import block
|
| 4 |
+
from mitmproxy.addons import blocklist
|
| 5 |
+
from mitmproxy.addons import browser
|
| 6 |
+
from mitmproxy.addons import clientplayback
|
| 7 |
+
from mitmproxy.addons import command_history
|
| 8 |
+
from mitmproxy.addons import comment
|
| 9 |
+
from mitmproxy.addons import core
|
| 10 |
+
from mitmproxy.addons import cut
|
| 11 |
+
from mitmproxy.addons import disable_h2c
|
| 12 |
+
from mitmproxy.addons import dns_resolver
|
| 13 |
+
from mitmproxy.addons import export
|
| 14 |
+
from mitmproxy.addons import maplocal
|
| 15 |
+
from mitmproxy.addons import mapremote
|
| 16 |
+
from mitmproxy.addons import modifybody
|
| 17 |
+
from mitmproxy.addons import modifyheaders
|
| 18 |
+
from mitmproxy.addons import next_layer
|
| 19 |
+
from mitmproxy.addons import onboarding
|
| 20 |
+
from mitmproxy.addons import proxyauth
|
| 21 |
+
from mitmproxy.addons import proxyserver
|
| 22 |
+
from mitmproxy.addons import save
|
| 23 |
+
from mitmproxy.addons import savehar
|
| 24 |
+
from mitmproxy.addons import script
|
| 25 |
+
from mitmproxy.addons import serverplayback
|
| 26 |
+
from mitmproxy.addons import stickyauth
|
| 27 |
+
from mitmproxy.addons import stickycookie
|
| 28 |
+
from mitmproxy.addons import strip_dns_https_records
|
| 29 |
+
from mitmproxy.addons import tlsconfig
|
| 30 |
+
from mitmproxy.addons import update_alt_svc
|
| 31 |
+
from mitmproxy.addons import upstream_auth
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def default_addons():
|
| 35 |
+
return [
|
| 36 |
+
core.Core(),
|
| 37 |
+
browser.Browser(),
|
| 38 |
+
block.Block(),
|
| 39 |
+
strip_dns_https_records.StripDnsHttpsRecords(),
|
| 40 |
+
blocklist.BlockList(),
|
| 41 |
+
anticache.AntiCache(),
|
| 42 |
+
anticomp.AntiComp(),
|
| 43 |
+
clientplayback.ClientPlayback(),
|
| 44 |
+
command_history.CommandHistory(),
|
| 45 |
+
comment.Comment(),
|
| 46 |
+
cut.Cut(),
|
| 47 |
+
disable_h2c.DisableH2C(),
|
| 48 |
+
export.Export(),
|
| 49 |
+
onboarding.Onboarding(),
|
| 50 |
+
proxyauth.ProxyAuth(),
|
| 51 |
+
proxyserver.Proxyserver(),
|
| 52 |
+
script.ScriptLoader(),
|
| 53 |
+
dns_resolver.DnsResolver(),
|
| 54 |
+
next_layer.NextLayer(),
|
| 55 |
+
serverplayback.ServerPlayback(),
|
| 56 |
+
mapremote.MapRemote(),
|
| 57 |
+
maplocal.MapLocal(),
|
| 58 |
+
modifybody.ModifyBody(),
|
| 59 |
+
modifyheaders.ModifyHeaders(),
|
| 60 |
+
stickyauth.StickyAuth(),
|
| 61 |
+
stickycookie.StickyCookie(),
|
| 62 |
+
save.Save(),
|
| 63 |
+
savehar.SaveHar(),
|
| 64 |
+
tlsconfig.TlsConfig(),
|
| 65 |
+
upstream_auth.UpstreamAuth(),
|
| 66 |
+
update_alt_svc.UpdateAltSvc(),
|
| 67 |
+
]
|
python/user_packages/Python313/site-packages/mitmproxy/addons/anticache.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mitmproxy import ctx
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class AntiCache:
|
| 5 |
+
def load(self, loader):
|
| 6 |
+
loader.add_option(
|
| 7 |
+
"anticache",
|
| 8 |
+
bool,
|
| 9 |
+
False,
|
| 10 |
+
"""
|
| 11 |
+
Strip out request headers that might cause the server to return
|
| 12 |
+
304-not-modified.
|
| 13 |
+
""",
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
def request(self, flow):
|
| 17 |
+
if ctx.options.anticache:
|
| 18 |
+
flow.request.anticache()
|
python/user_packages/Python313/site-packages/mitmproxy/addons/anticomp.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mitmproxy import ctx
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class AntiComp:
|
| 5 |
+
def load(self, loader):
|
| 6 |
+
loader.add_option(
|
| 7 |
+
"anticomp",
|
| 8 |
+
bool,
|
| 9 |
+
False,
|
| 10 |
+
"Try to convince servers to send us un-compressed data.",
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
def request(self, flow):
|
| 14 |
+
if ctx.options.anticomp:
|
| 15 |
+
flow.request.anticomp()
|
python/user_packages/Python313/site-packages/mitmproxy/addons/asgiapp.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import urllib.parse
|
| 4 |
+
|
| 5 |
+
import asgiref.compatibility
|
| 6 |
+
import asgiref.wsgi
|
| 7 |
+
|
| 8 |
+
from mitmproxy import ctx
|
| 9 |
+
from mitmproxy import http
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ASGIApp:
|
| 15 |
+
"""
|
| 16 |
+
An addon that hosts an ASGI/WSGI HTTP app within mitmproxy, at a specified hostname and port.
|
| 17 |
+
|
| 18 |
+
Some important caveats:
|
| 19 |
+
- This implementation will block and wait until the entire HTTP response is completed before sending out data.
|
| 20 |
+
- It currently only implements the HTTP protocol (Lifespan and WebSocket are unimplemented).
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, asgi_app, host: str, port: int | None):
|
| 24 |
+
asgi_app = asgiref.compatibility.guarantee_single_callable(asgi_app)
|
| 25 |
+
self.asgi_app, self.host, self.port = asgi_app, host, port
|
| 26 |
+
|
| 27 |
+
@property
|
| 28 |
+
def name(self) -> str:
|
| 29 |
+
return f"asgiapp:{self.host}:{self.port}"
|
| 30 |
+
|
| 31 |
+
def should_serve(self, flow: http.HTTPFlow) -> bool:
|
| 32 |
+
return bool(
|
| 33 |
+
flow.request.pretty_host == self.host
|
| 34 |
+
and (self.port is None or flow.request.port == self.port)
|
| 35 |
+
and flow.live
|
| 36 |
+
and not flow.error
|
| 37 |
+
and not flow.response
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
async def request(self, flow: http.HTTPFlow) -> None:
|
| 41 |
+
if self.should_serve(flow):
|
| 42 |
+
await serve(self.asgi_app, flow)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class WSGIApp(ASGIApp):
|
| 46 |
+
def __init__(self, wsgi_app, host: str, port: int | None):
|
| 47 |
+
asgi_app = asgiref.wsgi.WsgiToAsgi(wsgi_app)
|
| 48 |
+
super().__init__(asgi_app, host, port)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
HTTP_VERSION_MAP = {
|
| 52 |
+
"HTTP/1.0": "1.0",
|
| 53 |
+
"HTTP/1.1": "1.1",
|
| 54 |
+
"HTTP/2.0": "2",
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def make_scope(flow: http.HTTPFlow) -> dict:
|
| 59 |
+
# %3F is a quoted question mark
|
| 60 |
+
quoted_path = urllib.parse.quote_from_bytes(flow.request.data.path).split(
|
| 61 |
+
"%3F", maxsplit=1
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# (Unicode string) – HTTP request target excluding any query string, with percent-encoded
|
| 65 |
+
# sequences and UTF-8 byte sequences decoded into characters.
|
| 66 |
+
path = quoted_path[0]
|
| 67 |
+
|
| 68 |
+
# (byte string) – URL portion after the ?, percent-encoded.
|
| 69 |
+
query_string: bytes
|
| 70 |
+
if len(quoted_path) > 1:
|
| 71 |
+
query_string = urllib.parse.unquote(quoted_path[1]).encode()
|
| 72 |
+
else:
|
| 73 |
+
query_string = b""
|
| 74 |
+
|
| 75 |
+
return {
|
| 76 |
+
"type": "http",
|
| 77 |
+
"asgi": {
|
| 78 |
+
"version": "3.0",
|
| 79 |
+
"spec_version": "2.1",
|
| 80 |
+
},
|
| 81 |
+
"http_version": HTTP_VERSION_MAP.get(flow.request.http_version, "1.1"),
|
| 82 |
+
"method": flow.request.method,
|
| 83 |
+
"scheme": flow.request.scheme.upper(),
|
| 84 |
+
"path": path,
|
| 85 |
+
"raw_path": flow.request.path,
|
| 86 |
+
"query_string": query_string,
|
| 87 |
+
"headers": [
|
| 88 |
+
(name.lower(), value) for (name, value) in flow.request.headers.fields
|
| 89 |
+
],
|
| 90 |
+
"client": flow.client_conn.peername,
|
| 91 |
+
"extensions": {
|
| 92 |
+
"mitmproxy.master": ctx.master,
|
| 93 |
+
},
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
async def serve(app, flow: http.HTTPFlow):
|
| 98 |
+
"""
|
| 99 |
+
Serves app on flow.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
scope = make_scope(flow)
|
| 103 |
+
done = asyncio.Event()
|
| 104 |
+
received_body = False
|
| 105 |
+
sent_response = False
|
| 106 |
+
|
| 107 |
+
async def receive():
|
| 108 |
+
nonlocal received_body
|
| 109 |
+
if not received_body:
|
| 110 |
+
received_body = True
|
| 111 |
+
return {
|
| 112 |
+
"type": "http.request",
|
| 113 |
+
"body": flow.request.raw_content,
|
| 114 |
+
}
|
| 115 |
+
else: # pragma: no cover
|
| 116 |
+
# We really don't expect this to be called a second time, but what to do?
|
| 117 |
+
# We just wait until the request is done before we continue here with sending a disconnect.
|
| 118 |
+
await done.wait()
|
| 119 |
+
return {"type": "http.disconnect"}
|
| 120 |
+
|
| 121 |
+
async def send(event):
|
| 122 |
+
if event["type"] == "http.response.start":
|
| 123 |
+
flow.response = http.Response.make(
|
| 124 |
+
event["status"], b"", event.get("headers", [])
|
| 125 |
+
)
|
| 126 |
+
flow.response.decode()
|
| 127 |
+
elif event["type"] == "http.response.body":
|
| 128 |
+
assert flow.response
|
| 129 |
+
flow.response.content += event.get("body", b"")
|
| 130 |
+
if not event.get("more_body", False):
|
| 131 |
+
nonlocal sent_response
|
| 132 |
+
sent_response = True
|
| 133 |
+
else:
|
| 134 |
+
raise AssertionError(f"Unexpected event: {event['type']}")
|
| 135 |
+
|
| 136 |
+
try:
|
| 137 |
+
await app(scope, receive, send)
|
| 138 |
+
if not sent_response:
|
| 139 |
+
raise RuntimeError(f"no response sent.")
|
| 140 |
+
except Exception as e:
|
| 141 |
+
logger.exception(f"Error in asgi app: {e}")
|
| 142 |
+
flow.response = http.Response.make(500, b"ASGI Error.")
|
| 143 |
+
finally:
|
| 144 |
+
done.set()
|
python/user_packages/Python313/site-packages/mitmproxy/addons/block.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ipaddress
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
from mitmproxy import ctx
|
| 5 |
+
from mitmproxy.proxy import mode_specs
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Block:
|
| 9 |
+
def load(self, loader):
|
| 10 |
+
loader.add_option(
|
| 11 |
+
"block_global",
|
| 12 |
+
bool,
|
| 13 |
+
True,
|
| 14 |
+
"""
|
| 15 |
+
Block connections from public IP addresses.
|
| 16 |
+
""",
|
| 17 |
+
)
|
| 18 |
+
loader.add_option(
|
| 19 |
+
"block_private",
|
| 20 |
+
bool,
|
| 21 |
+
False,
|
| 22 |
+
"""
|
| 23 |
+
Block connections from local (private) IP addresses.
|
| 24 |
+
This option does not affect loopback addresses (connections from the local machine),
|
| 25 |
+
which are always permitted.
|
| 26 |
+
""",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def client_connected(self, client):
|
| 30 |
+
parts = client.peername[0].rsplit("%", 1)
|
| 31 |
+
address = ipaddress.ip_address(parts[0])
|
| 32 |
+
if isinstance(address, ipaddress.IPv6Address):
|
| 33 |
+
address = address.ipv4_mapped or address
|
| 34 |
+
|
| 35 |
+
if address.is_loopback or isinstance(client.proxy_mode, mode_specs.LocalMode):
|
| 36 |
+
return
|
| 37 |
+
|
| 38 |
+
if ctx.options.block_private and address.is_private:
|
| 39 |
+
logging.warning(
|
| 40 |
+
f"Client connection from {client.peername[0]} killed by block_private option."
|
| 41 |
+
)
|
| 42 |
+
client.error = "Connection killed by block_private."
|
| 43 |
+
|
| 44 |
+
if ctx.options.block_global and address.is_global:
|
| 45 |
+
logging.warning(
|
| 46 |
+
f"Client connection from {client.peername[0]} killed by block_global option."
|
| 47 |
+
)
|
| 48 |
+
client.error = "Connection killed by block_global."
|
python/user_packages/Python313/site-packages/mitmproxy/addons/blocklist.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from typing import NamedTuple
|
| 3 |
+
|
| 4 |
+
from mitmproxy import ctx
|
| 5 |
+
from mitmproxy import exceptions
|
| 6 |
+
from mitmproxy import flowfilter
|
| 7 |
+
from mitmproxy import http
|
| 8 |
+
from mitmproxy import version
|
| 9 |
+
from mitmproxy.net.http.status_codes import NO_RESPONSE
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class BlockSpec(NamedTuple):
|
| 13 |
+
matches: flowfilter.TFilter
|
| 14 |
+
status_code: int
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def parse_spec(option: str) -> BlockSpec:
|
| 18 |
+
"""
|
| 19 |
+
Parses strings in the following format, enforces number of segments:
|
| 20 |
+
|
| 21 |
+
/flow-filter/status
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
sep, rem = option[0], option[1:]
|
| 25 |
+
|
| 26 |
+
parts = rem.split(sep, 2)
|
| 27 |
+
if len(parts) != 2:
|
| 28 |
+
raise ValueError("Invalid number of parameters (2 are expected)")
|
| 29 |
+
flow_patt, status = parts
|
| 30 |
+
try:
|
| 31 |
+
status_code = int(status)
|
| 32 |
+
except ValueError:
|
| 33 |
+
raise ValueError(f"Invalid HTTP status code: {status}")
|
| 34 |
+
flow_filter = flowfilter.parse(flow_patt)
|
| 35 |
+
|
| 36 |
+
return BlockSpec(matches=flow_filter, status_code=status_code)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BlockList:
|
| 40 |
+
def __init__(self) -> None:
|
| 41 |
+
self.items: list[BlockSpec] = []
|
| 42 |
+
|
| 43 |
+
def load(self, loader):
|
| 44 |
+
loader.add_option(
|
| 45 |
+
"block_list",
|
| 46 |
+
Sequence[str],
|
| 47 |
+
[],
|
| 48 |
+
"""
|
| 49 |
+
Block matching requests and return an empty response with the specified HTTP status.
|
| 50 |
+
Option syntax is "/flow-filter/status-code", where flow-filter describes
|
| 51 |
+
which requests this rule should be applied to and status-code is the HTTP status code to return for
|
| 52 |
+
blocked requests. The separator ("/" in the example) can be any character.
|
| 53 |
+
Setting a non-standard status code of 444 will close the connection without sending a response.
|
| 54 |
+
""",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def configure(self, updated):
|
| 58 |
+
if "block_list" in updated:
|
| 59 |
+
self.items = []
|
| 60 |
+
for option in ctx.options.block_list:
|
| 61 |
+
try:
|
| 62 |
+
spec = parse_spec(option)
|
| 63 |
+
except ValueError as e:
|
| 64 |
+
raise exceptions.OptionsError(
|
| 65 |
+
f"Cannot parse block_list option {option}: {e}"
|
| 66 |
+
) from e
|
| 67 |
+
self.items.append(spec)
|
| 68 |
+
|
| 69 |
+
def request(self, flow: http.HTTPFlow) -> None:
|
| 70 |
+
if flow.response or flow.error or not flow.live:
|
| 71 |
+
return
|
| 72 |
+
|
| 73 |
+
for spec in self.items:
|
| 74 |
+
if spec.matches(flow):
|
| 75 |
+
flow.metadata["blocklisted"] = True
|
| 76 |
+
if spec.status_code == NO_RESPONSE:
|
| 77 |
+
flow.kill()
|
| 78 |
+
else:
|
| 79 |
+
flow.response = http.Response.make(
|
| 80 |
+
spec.status_code, headers={"Server": version.MITMPROXY}
|
| 81 |
+
)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/browser.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import shutil
|
| 3 |
+
import subprocess
|
| 4 |
+
import tempfile
|
| 5 |
+
|
| 6 |
+
from mitmproxy import command
|
| 7 |
+
from mitmproxy import ctx
|
| 8 |
+
from mitmproxy.log import ALERT
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def find_executable_cmd(*search_paths) -> list[str] | None:
|
| 12 |
+
for browser in search_paths:
|
| 13 |
+
if shutil.which(browser):
|
| 14 |
+
return [browser]
|
| 15 |
+
|
| 16 |
+
return None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def find_flatpak_cmd(*search_paths) -> list[str] | None:
|
| 20 |
+
if shutil.which("flatpak"):
|
| 21 |
+
for browser in search_paths:
|
| 22 |
+
if (
|
| 23 |
+
subprocess.run(
|
| 24 |
+
["flatpak", "info", browser],
|
| 25 |
+
stdout=subprocess.DEVNULL,
|
| 26 |
+
stderr=subprocess.DEVNULL,
|
| 27 |
+
).returncode
|
| 28 |
+
== 0
|
| 29 |
+
):
|
| 30 |
+
return ["flatpak", "run", "-p", browser]
|
| 31 |
+
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Browser:
|
| 36 |
+
browser: list[subprocess.Popen] = []
|
| 37 |
+
tdir: list[tempfile.TemporaryDirectory] = []
|
| 38 |
+
|
| 39 |
+
@command.command("browser.start")
|
| 40 |
+
def start(self, browser: str = "chrome") -> None:
|
| 41 |
+
if len(self.browser) > 0:
|
| 42 |
+
logging.log(ALERT, "Starting additional browser")
|
| 43 |
+
|
| 44 |
+
if browser in ("chrome", "chromium"):
|
| 45 |
+
self.launch_chrome()
|
| 46 |
+
elif browser == "firefox":
|
| 47 |
+
self.launch_firefox()
|
| 48 |
+
else:
|
| 49 |
+
logging.log(ALERT, "Invalid browser name.")
|
| 50 |
+
|
| 51 |
+
def launch_chrome(self) -> None:
|
| 52 |
+
"""
|
| 53 |
+
Start an isolated instance of Chrome that points to the currently
|
| 54 |
+
running proxy.
|
| 55 |
+
"""
|
| 56 |
+
cmd = find_executable_cmd(
|
| 57 |
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
| 58 |
+
# https://stackoverflow.com/questions/40674914/google-chrome-path-in-windows-10
|
| 59 |
+
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
|
| 60 |
+
r"C:\Program Files (x86)\Google\Application\chrome.exe",
|
| 61 |
+
# Linux binary names from Python's webbrowser module.
|
| 62 |
+
"google-chrome",
|
| 63 |
+
"google-chrome-stable",
|
| 64 |
+
"chrome",
|
| 65 |
+
"chromium",
|
| 66 |
+
"chromium-browser",
|
| 67 |
+
"google-chrome-unstable",
|
| 68 |
+
) or find_flatpak_cmd(
|
| 69 |
+
"com.google.Chrome",
|
| 70 |
+
"org.chromium.Chromium",
|
| 71 |
+
"com.github.Eloston.UngoogledChromium",
|
| 72 |
+
"com.google.ChromeDev",
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
if not cmd:
|
| 76 |
+
logging.log(
|
| 77 |
+
ALERT, "Your platform is not supported yet - please submit a patch."
|
| 78 |
+
)
|
| 79 |
+
return
|
| 80 |
+
|
| 81 |
+
tdir = tempfile.TemporaryDirectory()
|
| 82 |
+
self.tdir.append(tdir)
|
| 83 |
+
self.browser.append(
|
| 84 |
+
subprocess.Popen(
|
| 85 |
+
[
|
| 86 |
+
*cmd,
|
| 87 |
+
"--user-data-dir=%s" % str(tdir.name),
|
| 88 |
+
"--proxy-server={}:{}".format(
|
| 89 |
+
ctx.options.listen_host or "127.0.0.1",
|
| 90 |
+
ctx.options.listen_port or "8080",
|
| 91 |
+
),
|
| 92 |
+
"--disable-fre",
|
| 93 |
+
"--no-default-browser-check",
|
| 94 |
+
"--no-first-run",
|
| 95 |
+
"--disable-extensions",
|
| 96 |
+
"about:blank",
|
| 97 |
+
],
|
| 98 |
+
stdout=subprocess.DEVNULL,
|
| 99 |
+
stderr=subprocess.DEVNULL,
|
| 100 |
+
)
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def launch_firefox(self) -> None:
|
| 104 |
+
"""
|
| 105 |
+
Start an isolated instance of Firefox that points to the currently
|
| 106 |
+
running proxy.
|
| 107 |
+
"""
|
| 108 |
+
cmd = find_executable_cmd(
|
| 109 |
+
"/Applications/Firefox.app/Contents/MacOS/firefox",
|
| 110 |
+
r"C:\Program Files\Mozilla Firefox\firefox.exe",
|
| 111 |
+
"firefox",
|
| 112 |
+
"mozilla-firefox",
|
| 113 |
+
"mozilla",
|
| 114 |
+
) or find_flatpak_cmd("org.mozilla.firefox")
|
| 115 |
+
|
| 116 |
+
if not cmd:
|
| 117 |
+
logging.log(
|
| 118 |
+
ALERT, "Your platform is not supported yet - please submit a patch."
|
| 119 |
+
)
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
host = ctx.options.listen_host or "127.0.0.1"
|
| 123 |
+
port = ctx.options.listen_port or 8080
|
| 124 |
+
prefs = [
|
| 125 |
+
'user_pref("datareporting.policy.firstRunURL", "");',
|
| 126 |
+
'user_pref("network.proxy.type", 1);',
|
| 127 |
+
'user_pref("network.proxy.share_proxy_settings", true);',
|
| 128 |
+
'user_pref("datareporting.healthreport.uploadEnabled", false);',
|
| 129 |
+
'user_pref("app.normandy.enabled", false);',
|
| 130 |
+
'user_pref("app.update.auto", false);',
|
| 131 |
+
'user_pref("app.update.enabled", false);',
|
| 132 |
+
'user_pref("app.update.autoInstallEnabled", false);',
|
| 133 |
+
'user_pref("app.shield.optoutstudies.enabled", false);'
|
| 134 |
+
'user_pref("extensions.blocklist.enabled", false);',
|
| 135 |
+
'user_pref("browser.safebrowsing.downloads.remote.enabled", false);',
|
| 136 |
+
'user_pref("browser.region.network.url", "");',
|
| 137 |
+
'user_pref("browser.region.update.enabled", false);',
|
| 138 |
+
'user_pref("browser.region.local-geocoding", false);',
|
| 139 |
+
'user_pref("extensions.pocket.enabled", false);',
|
| 140 |
+
'user_pref("network.captive-portal-service.enabled", false);',
|
| 141 |
+
'user_pref("network.connectivity-service.enabled", false);',
|
| 142 |
+
'user_pref("toolkit.telemetry.server", "");',
|
| 143 |
+
'user_pref("dom.push.serverURL", "");',
|
| 144 |
+
'user_pref("services.settings.enabled", false);',
|
| 145 |
+
'user_pref("browser.newtab.preload", false);',
|
| 146 |
+
'user_pref("browser.safebrowsing.provider.google4.updateURL", "");',
|
| 147 |
+
'user_pref("browser.safebrowsing.provider.mozilla.updateURL", "");',
|
| 148 |
+
'user_pref("browser.newtabpage.activity-stream.feeds.topsites", false);',
|
| 149 |
+
'user_pref("browser.newtabpage.activity-stream.default.sites", "");',
|
| 150 |
+
'user_pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false);',
|
| 151 |
+
'user_pref("browser.bookmarks.restore_default_bookmarks", false);',
|
| 152 |
+
'user_pref("browser.bookmarks.file", "");',
|
| 153 |
+
]
|
| 154 |
+
for service in ("http", "ssl"):
|
| 155 |
+
prefs += [
|
| 156 |
+
f'user_pref("network.proxy.{service}", "{host}");',
|
| 157 |
+
f'user_pref("network.proxy.{service}_port", {port});',
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
tdir = tempfile.TemporaryDirectory()
|
| 161 |
+
|
| 162 |
+
with open(tdir.name + "/prefs.js", "w") as file:
|
| 163 |
+
file.writelines(prefs)
|
| 164 |
+
|
| 165 |
+
self.tdir.append(tdir)
|
| 166 |
+
self.browser.append(
|
| 167 |
+
subprocess.Popen(
|
| 168 |
+
[
|
| 169 |
+
*cmd,
|
| 170 |
+
"--profile",
|
| 171 |
+
str(tdir.name),
|
| 172 |
+
"--new-window",
|
| 173 |
+
"about:blank",
|
| 174 |
+
],
|
| 175 |
+
stdout=subprocess.DEVNULL,
|
| 176 |
+
stderr=subprocess.DEVNULL,
|
| 177 |
+
)
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def done(self):
|
| 181 |
+
for browser in self.browser:
|
| 182 |
+
browser.kill()
|
| 183 |
+
for tdir in self.tdir:
|
| 184 |
+
tdir.cleanup()
|
| 185 |
+
self.browser = []
|
| 186 |
+
self.tdir = []
|
python/user_packages/Python313/site-packages/mitmproxy/addons/clientplayback.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import logging
|
| 5 |
+
import time
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
from types import TracebackType
|
| 8 |
+
from typing import cast
|
| 9 |
+
from typing import Literal
|
| 10 |
+
|
| 11 |
+
import mitmproxy.types
|
| 12 |
+
from mitmproxy import command
|
| 13 |
+
from mitmproxy import ctx
|
| 14 |
+
from mitmproxy import exceptions
|
| 15 |
+
from mitmproxy import flow
|
| 16 |
+
from mitmproxy import http
|
| 17 |
+
from mitmproxy import io
|
| 18 |
+
from mitmproxy.connection import ConnectionState
|
| 19 |
+
from mitmproxy.connection import Server
|
| 20 |
+
from mitmproxy.hooks import UpdateHook
|
| 21 |
+
from mitmproxy.log import ALERT
|
| 22 |
+
from mitmproxy.options import Options
|
| 23 |
+
from mitmproxy.proxy import commands
|
| 24 |
+
from mitmproxy.proxy import events
|
| 25 |
+
from mitmproxy.proxy import layers
|
| 26 |
+
from mitmproxy.proxy import server
|
| 27 |
+
from mitmproxy.proxy.context import Context
|
| 28 |
+
from mitmproxy.proxy.layer import CommandGenerator
|
| 29 |
+
from mitmproxy.proxy.layers.http import HTTPMode
|
| 30 |
+
from mitmproxy.proxy.mode_specs import UpstreamMode
|
| 31 |
+
from mitmproxy.utils import asyncio_utils
|
| 32 |
+
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class MockServer(layers.http.HttpConnection):
|
| 37 |
+
"""
|
| 38 |
+
A mock HTTP "server" that just pretends it received a full HTTP request,
|
| 39 |
+
which is then processed by the proxy core.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
flow: http.HTTPFlow
|
| 43 |
+
|
| 44 |
+
def __init__(self, flow: http.HTTPFlow, context: Context):
|
| 45 |
+
super().__init__(context, context.client)
|
| 46 |
+
self.flow = flow
|
| 47 |
+
|
| 48 |
+
def _handle_event(self, event: events.Event) -> CommandGenerator[None]:
|
| 49 |
+
if isinstance(event, events.Start):
|
| 50 |
+
content = self.flow.request.raw_content
|
| 51 |
+
self.flow.request.timestamp_start = self.flow.request.timestamp_end = (
|
| 52 |
+
time.time()
|
| 53 |
+
)
|
| 54 |
+
yield layers.http.ReceiveHttp(
|
| 55 |
+
layers.http.RequestHeaders(
|
| 56 |
+
1,
|
| 57 |
+
self.flow.request,
|
| 58 |
+
end_stream=not (content or self.flow.request.trailers),
|
| 59 |
+
replay_flow=self.flow,
|
| 60 |
+
)
|
| 61 |
+
)
|
| 62 |
+
if content:
|
| 63 |
+
yield layers.http.ReceiveHttp(layers.http.RequestData(1, content))
|
| 64 |
+
if self.flow.request.trailers: # pragma: no cover
|
| 65 |
+
# TODO: Cover this once we support HTTP/1 trailers.
|
| 66 |
+
yield layers.http.ReceiveHttp(
|
| 67 |
+
layers.http.RequestTrailers(1, self.flow.request.trailers)
|
| 68 |
+
)
|
| 69 |
+
yield layers.http.ReceiveHttp(layers.http.RequestEndOfMessage(1))
|
| 70 |
+
elif isinstance(
|
| 71 |
+
event,
|
| 72 |
+
(
|
| 73 |
+
layers.http.ResponseHeaders,
|
| 74 |
+
layers.http.ResponseData,
|
| 75 |
+
layers.http.ResponseTrailers,
|
| 76 |
+
layers.http.ResponseEndOfMessage,
|
| 77 |
+
layers.http.ResponseProtocolError,
|
| 78 |
+
),
|
| 79 |
+
):
|
| 80 |
+
pass
|
| 81 |
+
else: # pragma: no cover
|
| 82 |
+
logger.warning(f"Unexpected event during replay: {event}")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ReplayHandler(server.ConnectionHandler):
|
| 86 |
+
layer: layers.HttpLayer
|
| 87 |
+
|
| 88 |
+
def __init__(self, flow: http.HTTPFlow, options: Options) -> None:
|
| 89 |
+
client = flow.client_conn.copy()
|
| 90 |
+
client.state = ConnectionState.OPEN
|
| 91 |
+
|
| 92 |
+
context = Context(client, options)
|
| 93 |
+
context.server = Server(address=(flow.request.host, flow.request.port))
|
| 94 |
+
if flow.request.scheme == "https":
|
| 95 |
+
context.server.tls = True
|
| 96 |
+
context.server.sni = flow.request.pretty_host
|
| 97 |
+
if options.mode and options.mode[0].startswith("upstream:"):
|
| 98 |
+
mode = UpstreamMode.parse(options.mode[0])
|
| 99 |
+
assert isinstance(mode, UpstreamMode) # remove once mypy supports Self.
|
| 100 |
+
context.server.via = flow.server_conn.via = (mode.scheme, mode.address)
|
| 101 |
+
|
| 102 |
+
super().__init__(context)
|
| 103 |
+
|
| 104 |
+
if options.mode and options.mode[0].startswith("upstream:"):
|
| 105 |
+
self.layer = layers.HttpLayer(context, HTTPMode.upstream)
|
| 106 |
+
else:
|
| 107 |
+
self.layer = layers.HttpLayer(context, HTTPMode.transparent)
|
| 108 |
+
self.layer.connections[client] = MockServer(flow, context.fork())
|
| 109 |
+
self.flow = flow
|
| 110 |
+
self.done = asyncio.Event()
|
| 111 |
+
|
| 112 |
+
async def replay(self) -> None:
|
| 113 |
+
await self.server_event(events.Start())
|
| 114 |
+
await self.done.wait()
|
| 115 |
+
|
| 116 |
+
def log(
|
| 117 |
+
self,
|
| 118 |
+
message: str,
|
| 119 |
+
level: int = logging.INFO,
|
| 120 |
+
exc_info: Literal[True]
|
| 121 |
+
| tuple[type[BaseException] | None, BaseException | None, TracebackType | None]
|
| 122 |
+
| None = None,
|
| 123 |
+
) -> None:
|
| 124 |
+
assert isinstance(level, int)
|
| 125 |
+
logger.log(level=level, msg=f"[replay] {message}")
|
| 126 |
+
|
| 127 |
+
async def handle_hook(self, hook: commands.StartHook) -> None:
|
| 128 |
+
(data,) = hook.args()
|
| 129 |
+
await ctx.master.addons.handle_lifecycle(hook)
|
| 130 |
+
if isinstance(data, flow.Flow):
|
| 131 |
+
await data.wait_for_resume()
|
| 132 |
+
if isinstance(hook, (layers.http.HttpResponseHook, layers.http.HttpErrorHook)):
|
| 133 |
+
if self.transports:
|
| 134 |
+
# close server connections
|
| 135 |
+
for x in self.transports.values():
|
| 136 |
+
if x.handler:
|
| 137 |
+
x.handler.cancel()
|
| 138 |
+
await asyncio.wait(
|
| 139 |
+
[x.handler for x in self.transports.values() if x.handler]
|
| 140 |
+
)
|
| 141 |
+
# signal completion
|
| 142 |
+
self.done.set()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class ClientPlayback:
|
| 146 |
+
playback_task: asyncio.Task | None = None
|
| 147 |
+
inflight: http.HTTPFlow | None
|
| 148 |
+
queue: asyncio.Queue
|
| 149 |
+
options: Options
|
| 150 |
+
replay_tasks: set[asyncio.Task]
|
| 151 |
+
|
| 152 |
+
def __init__(self):
|
| 153 |
+
self.queue = asyncio.Queue()
|
| 154 |
+
self.inflight = None
|
| 155 |
+
self.task = None
|
| 156 |
+
self.replay_tasks = set()
|
| 157 |
+
|
| 158 |
+
def running(self):
|
| 159 |
+
self.options = ctx.options
|
| 160 |
+
self.playback_task = asyncio_utils.create_task(
|
| 161 |
+
self.playback(),
|
| 162 |
+
name="client playback",
|
| 163 |
+
keep_ref=False,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
async def done(self):
|
| 167 |
+
if self.playback_task:
|
| 168 |
+
self.playback_task.cancel()
|
| 169 |
+
try:
|
| 170 |
+
await self.playback_task
|
| 171 |
+
except asyncio.CancelledError:
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
async def playback(self):
|
| 175 |
+
while True:
|
| 176 |
+
self.inflight = await self.queue.get()
|
| 177 |
+
try:
|
| 178 |
+
assert self.inflight
|
| 179 |
+
h = ReplayHandler(self.inflight, self.options)
|
| 180 |
+
if ctx.options.client_replay_concurrency == -1:
|
| 181 |
+
t = asyncio_utils.create_task(
|
| 182 |
+
h.replay(),
|
| 183 |
+
name="client playback awaiting response",
|
| 184 |
+
keep_ref=False,
|
| 185 |
+
)
|
| 186 |
+
# keep a reference so this is not garbage collected
|
| 187 |
+
self.replay_tasks.add(t)
|
| 188 |
+
t.add_done_callback(self.replay_tasks.remove)
|
| 189 |
+
else:
|
| 190 |
+
await h.replay()
|
| 191 |
+
except Exception:
|
| 192 |
+
logger.exception(f"Client replay has crashed!")
|
| 193 |
+
self.queue.task_done()
|
| 194 |
+
self.inflight = None
|
| 195 |
+
|
| 196 |
+
def check(self, f: flow.Flow) -> str | None:
|
| 197 |
+
if f.live or f == self.inflight:
|
| 198 |
+
return "Can't replay live flow."
|
| 199 |
+
if f.intercepted:
|
| 200 |
+
return "Can't replay intercepted flow."
|
| 201 |
+
if isinstance(f, http.HTTPFlow):
|
| 202 |
+
if not f.request:
|
| 203 |
+
return "Can't replay flow with missing request."
|
| 204 |
+
if f.request.raw_content is None:
|
| 205 |
+
return "Can't replay flow with missing content."
|
| 206 |
+
if f.websocket is not None:
|
| 207 |
+
return "Can't replay WebSocket flows."
|
| 208 |
+
else:
|
| 209 |
+
return "Can only replay HTTP flows."
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
+
def load(self, loader):
|
| 213 |
+
loader.add_option(
|
| 214 |
+
"client_replay",
|
| 215 |
+
Sequence[str],
|
| 216 |
+
[],
|
| 217 |
+
"Replay client requests from a saved file.",
|
| 218 |
+
)
|
| 219 |
+
loader.add_option(
|
| 220 |
+
"client_replay_concurrency",
|
| 221 |
+
int,
|
| 222 |
+
1,
|
| 223 |
+
"Concurrency limit on in-flight client replay requests. Currently the only valid values are 1 and -1 (no limit).",
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
def configure(self, updated):
|
| 227 |
+
if "client_replay" in updated and ctx.options.client_replay:
|
| 228 |
+
try:
|
| 229 |
+
flows = io.read_flows_from_paths(ctx.options.client_replay)
|
| 230 |
+
except exceptions.FlowReadException as e:
|
| 231 |
+
raise exceptions.OptionsError(str(e))
|
| 232 |
+
self.start_replay(flows)
|
| 233 |
+
|
| 234 |
+
if "client_replay_concurrency" in updated:
|
| 235 |
+
if ctx.options.client_replay_concurrency not in [-1, 1]:
|
| 236 |
+
raise exceptions.OptionsError(
|
| 237 |
+
"Currently the only valid client_replay_concurrency values are -1 and 1."
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
@command.command("replay.client.count")
|
| 241 |
+
def count(self) -> int:
|
| 242 |
+
"""
|
| 243 |
+
Approximate number of flows queued for replay.
|
| 244 |
+
"""
|
| 245 |
+
return self.queue.qsize() + int(bool(self.inflight))
|
| 246 |
+
|
| 247 |
+
@command.command("replay.client.stop")
|
| 248 |
+
def stop_replay(self) -> None:
|
| 249 |
+
"""
|
| 250 |
+
Clear the replay queue.
|
| 251 |
+
"""
|
| 252 |
+
updated = []
|
| 253 |
+
while True:
|
| 254 |
+
try:
|
| 255 |
+
f = self.queue.get_nowait()
|
| 256 |
+
except asyncio.QueueEmpty:
|
| 257 |
+
break
|
| 258 |
+
else:
|
| 259 |
+
self.queue.task_done()
|
| 260 |
+
f.revert()
|
| 261 |
+
updated.append(f)
|
| 262 |
+
|
| 263 |
+
ctx.master.addons.trigger(UpdateHook(updated))
|
| 264 |
+
logger.log(ALERT, "Client replay queue cleared.")
|
| 265 |
+
|
| 266 |
+
@command.command("replay.client")
|
| 267 |
+
def start_replay(self, flows: Sequence[flow.Flow]) -> None:
|
| 268 |
+
"""
|
| 269 |
+
Add flows to the replay queue, skipping flows that can't be replayed.
|
| 270 |
+
"""
|
| 271 |
+
updated: list[http.HTTPFlow] = []
|
| 272 |
+
for f in flows:
|
| 273 |
+
err = self.check(f)
|
| 274 |
+
if err:
|
| 275 |
+
logger.warning(err)
|
| 276 |
+
continue
|
| 277 |
+
|
| 278 |
+
http_flow = cast(http.HTTPFlow, f)
|
| 279 |
+
|
| 280 |
+
# Prepare the flow for replay
|
| 281 |
+
http_flow.backup()
|
| 282 |
+
http_flow.is_replay = "request"
|
| 283 |
+
http_flow.response = None
|
| 284 |
+
http_flow.error = None
|
| 285 |
+
self.queue.put_nowait(http_flow)
|
| 286 |
+
updated.append(http_flow)
|
| 287 |
+
ctx.master.addons.trigger(UpdateHook(updated))
|
| 288 |
+
|
| 289 |
+
@command.command("replay.client.file")
|
| 290 |
+
def load_file(self, path: mitmproxy.types.Path) -> None:
|
| 291 |
+
"""
|
| 292 |
+
Load flows from file, and add them to the replay queue.
|
| 293 |
+
"""
|
| 294 |
+
try:
|
| 295 |
+
flows = io.read_flows_from_paths([path])
|
| 296 |
+
except exceptions.FlowReadException as e:
|
| 297 |
+
raise exceptions.CommandError(str(e))
|
| 298 |
+
self.start_replay(flows)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/command_history.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import pathlib
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
|
| 6 |
+
from mitmproxy import command
|
| 7 |
+
from mitmproxy import ctx
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CommandHistory:
|
| 11 |
+
VACUUM_SIZE = 1024
|
| 12 |
+
|
| 13 |
+
def __init__(self) -> None:
|
| 14 |
+
self.history: list[str] = []
|
| 15 |
+
self.filtered_history: list[str] = [""]
|
| 16 |
+
self.current_index: int = 0
|
| 17 |
+
|
| 18 |
+
def load(self, loader):
|
| 19 |
+
loader.add_option(
|
| 20 |
+
"command_history",
|
| 21 |
+
bool,
|
| 22 |
+
True,
|
| 23 |
+
"""Persist command history between mitmproxy invocations.""",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def history_file(self) -> pathlib.Path:
|
| 28 |
+
return pathlib.Path(os.path.expanduser(ctx.options.confdir)) / "command_history"
|
| 29 |
+
|
| 30 |
+
def running(self):
|
| 31 |
+
# FIXME: We have a weird bug where the contract for configure is not followed and it is never called with
|
| 32 |
+
# confdir or command_history as updated.
|
| 33 |
+
self.configure("command_history") # pragma: no cover
|
| 34 |
+
|
| 35 |
+
def configure(self, updated):
|
| 36 |
+
if "command_history" in updated or "confdir" in updated:
|
| 37 |
+
if ctx.options.command_history and self.history_file.is_file():
|
| 38 |
+
self.history = self.history_file.read_text().splitlines()
|
| 39 |
+
self.set_filter("")
|
| 40 |
+
|
| 41 |
+
def done(self):
|
| 42 |
+
if ctx.options.command_history and len(self.history) >= self.VACUUM_SIZE:
|
| 43 |
+
# vacuum history so that it doesn't grow indefinitely.
|
| 44 |
+
history_str = "\n".join(self.history[-self.VACUUM_SIZE // 2 :]) + "\n"
|
| 45 |
+
try:
|
| 46 |
+
self.history_file.write_text(history_str)
|
| 47 |
+
except Exception as e:
|
| 48 |
+
logging.warning(f"Failed writing to {self.history_file}: {e}")
|
| 49 |
+
|
| 50 |
+
@command.command("commands.history.add")
|
| 51 |
+
def add_command(self, command: str) -> None:
|
| 52 |
+
if not command.strip():
|
| 53 |
+
return
|
| 54 |
+
|
| 55 |
+
self.history.append(command)
|
| 56 |
+
if ctx.options.command_history:
|
| 57 |
+
try:
|
| 58 |
+
with self.history_file.open("a") as f:
|
| 59 |
+
f.write(f"{command}\n")
|
| 60 |
+
except Exception as e:
|
| 61 |
+
logging.warning(f"Failed writing to {self.history_file}: {e}")
|
| 62 |
+
|
| 63 |
+
self.set_filter("")
|
| 64 |
+
|
| 65 |
+
@command.command("commands.history.get")
|
| 66 |
+
def get_history(self) -> Sequence[str]:
|
| 67 |
+
"""Get the entire command history."""
|
| 68 |
+
return self.history.copy()
|
| 69 |
+
|
| 70 |
+
@command.command("commands.history.clear")
|
| 71 |
+
def clear_history(self):
|
| 72 |
+
if self.history_file.exists():
|
| 73 |
+
try:
|
| 74 |
+
self.history_file.unlink()
|
| 75 |
+
except Exception as e:
|
| 76 |
+
logging.warning(f"Failed deleting {self.history_file}: {e}")
|
| 77 |
+
self.history = []
|
| 78 |
+
self.set_filter("")
|
| 79 |
+
|
| 80 |
+
# Functionality to provide a filtered list that can be iterated through.
|
| 81 |
+
|
| 82 |
+
@command.command("commands.history.filter")
|
| 83 |
+
def set_filter(self, prefix: str) -> None:
|
| 84 |
+
self.filtered_history = [cmd for cmd in self.history if cmd.startswith(prefix)]
|
| 85 |
+
self.filtered_history.append(prefix)
|
| 86 |
+
self.current_index = len(self.filtered_history) - 1
|
| 87 |
+
|
| 88 |
+
@command.command("commands.history.next")
|
| 89 |
+
def get_next(self) -> str:
|
| 90 |
+
self.current_index = min(self.current_index + 1, len(self.filtered_history) - 1)
|
| 91 |
+
return self.filtered_history[self.current_index]
|
| 92 |
+
|
| 93 |
+
@command.command("commands.history.prev")
|
| 94 |
+
def get_prev(self) -> str:
|
| 95 |
+
self.current_index = max(0, self.current_index - 1)
|
| 96 |
+
return self.filtered_history[self.current_index]
|
python/user_packages/Python313/site-packages/mitmproxy/addons/comment.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
|
| 3 |
+
from mitmproxy import command
|
| 4 |
+
from mitmproxy import ctx
|
| 5 |
+
from mitmproxy import flow
|
| 6 |
+
from mitmproxy.hooks import UpdateHook
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Comment:
|
| 10 |
+
@command.command("flow.comment")
|
| 11 |
+
def comment(self, flow: Sequence[flow.Flow], comment: str) -> None:
|
| 12 |
+
"Add a comment to a flow"
|
| 13 |
+
|
| 14 |
+
updated = []
|
| 15 |
+
for f in flow:
|
| 16 |
+
f.comment = comment
|
| 17 |
+
updated.append(f)
|
| 18 |
+
|
| 19 |
+
ctx.master.addons.trigger(UpdateHook(updated))
|
python/user_packages/Python313/site-packages/mitmproxy/addons/core.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
|
| 5 |
+
import mitmproxy.types
|
| 6 |
+
from mitmproxy import command
|
| 7 |
+
from mitmproxy import ctx
|
| 8 |
+
from mitmproxy import exceptions
|
| 9 |
+
from mitmproxy import flow
|
| 10 |
+
from mitmproxy import hooks
|
| 11 |
+
from mitmproxy import optmanager
|
| 12 |
+
from mitmproxy.log import ALERT
|
| 13 |
+
from mitmproxy.net.http import status_codes
|
| 14 |
+
from mitmproxy.utils import emoji
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
CONF_DIR = "~/.mitmproxy"
|
| 19 |
+
LISTEN_PORT = 8080
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Core:
|
| 23 |
+
def configure(self, updated):
|
| 24 |
+
opts = ctx.options
|
| 25 |
+
if opts.add_upstream_certs_to_client_chain and not opts.upstream_cert:
|
| 26 |
+
raise exceptions.OptionsError(
|
| 27 |
+
"add_upstream_certs_to_client_chain requires the upstream_cert option to be enabled."
|
| 28 |
+
)
|
| 29 |
+
if "client_certs" in updated:
|
| 30 |
+
if opts.client_certs:
|
| 31 |
+
client_certs = os.path.expanduser(opts.client_certs)
|
| 32 |
+
if not os.path.exists(client_certs):
|
| 33 |
+
raise exceptions.OptionsError(
|
| 34 |
+
f"Client certificate path does not exist: {opts.client_certs}"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
@command.command("set")
|
| 38 |
+
def set(self, option: str, *value: str) -> None:
|
| 39 |
+
"""
|
| 40 |
+
Set an option. When the value is omitted, booleans are set to true,
|
| 41 |
+
strings and integers are set to None (if permitted), and sequences
|
| 42 |
+
are emptied. Boolean values can be true, false or toggle.
|
| 43 |
+
Multiple values are concatenated with a single space.
|
| 44 |
+
"""
|
| 45 |
+
if value:
|
| 46 |
+
specs = [f"{option}={v}" for v in value]
|
| 47 |
+
else:
|
| 48 |
+
specs = [option]
|
| 49 |
+
try:
|
| 50 |
+
ctx.options.set(*specs)
|
| 51 |
+
except exceptions.OptionsError as e:
|
| 52 |
+
raise exceptions.CommandError(e) from e
|
| 53 |
+
|
| 54 |
+
@command.command("flow.resume")
|
| 55 |
+
def resume(self, flows: Sequence[flow.Flow]) -> None:
|
| 56 |
+
"""
|
| 57 |
+
Resume flows if they are intercepted.
|
| 58 |
+
"""
|
| 59 |
+
intercepted = [i for i in flows if i.intercepted]
|
| 60 |
+
for f in intercepted:
|
| 61 |
+
f.resume()
|
| 62 |
+
ctx.master.addons.trigger(hooks.UpdateHook(intercepted))
|
| 63 |
+
|
| 64 |
+
# FIXME: this will become view.mark later
|
| 65 |
+
@command.command("flow.mark")
|
| 66 |
+
def mark(self, flows: Sequence[flow.Flow], marker: mitmproxy.types.Marker) -> None:
|
| 67 |
+
"""
|
| 68 |
+
Mark flows.
|
| 69 |
+
"""
|
| 70 |
+
updated = []
|
| 71 |
+
if not (marker == "" or marker in emoji.emoji):
|
| 72 |
+
raise exceptions.CommandError(f"invalid marker value")
|
| 73 |
+
|
| 74 |
+
for i in flows:
|
| 75 |
+
i.marked = marker
|
| 76 |
+
updated.append(i)
|
| 77 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 78 |
+
|
| 79 |
+
# FIXME: this will become view.mark.toggle later
|
| 80 |
+
@command.command("flow.mark.toggle")
|
| 81 |
+
def mark_toggle(self, flows: Sequence[flow.Flow]) -> None:
|
| 82 |
+
"""
|
| 83 |
+
Toggle mark for flows.
|
| 84 |
+
"""
|
| 85 |
+
for i in flows:
|
| 86 |
+
if i.marked:
|
| 87 |
+
i.marked = ""
|
| 88 |
+
else:
|
| 89 |
+
i.marked = ":default:"
|
| 90 |
+
ctx.master.addons.trigger(hooks.UpdateHook(flows))
|
| 91 |
+
|
| 92 |
+
@command.command("flow.kill")
|
| 93 |
+
def kill(self, flows: Sequence[flow.Flow]) -> None:
|
| 94 |
+
"""
|
| 95 |
+
Kill running flows.
|
| 96 |
+
"""
|
| 97 |
+
updated = []
|
| 98 |
+
for f in flows:
|
| 99 |
+
if f.killable:
|
| 100 |
+
f.kill()
|
| 101 |
+
updated.append(f)
|
| 102 |
+
logger.log(ALERT, "Killed %s flows." % len(updated))
|
| 103 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 104 |
+
|
| 105 |
+
# FIXME: this will become view.revert later
|
| 106 |
+
@command.command("flow.revert")
|
| 107 |
+
def revert(self, flows: Sequence[flow.Flow]) -> None:
|
| 108 |
+
"""
|
| 109 |
+
Revert flow changes.
|
| 110 |
+
"""
|
| 111 |
+
updated = []
|
| 112 |
+
for f in flows:
|
| 113 |
+
if f.modified():
|
| 114 |
+
f.revert()
|
| 115 |
+
updated.append(f)
|
| 116 |
+
logger.log(ALERT, "Reverted %s flows." % len(updated))
|
| 117 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 118 |
+
|
| 119 |
+
@command.command("flow.set.options")
|
| 120 |
+
def flow_set_options(self) -> Sequence[str]:
|
| 121 |
+
return [
|
| 122 |
+
"host",
|
| 123 |
+
"status_code",
|
| 124 |
+
"method",
|
| 125 |
+
"path",
|
| 126 |
+
"url",
|
| 127 |
+
"reason",
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
@command.command("flow.set")
|
| 131 |
+
@command.argument("attr", type=mitmproxy.types.Choice("flow.set.options"))
|
| 132 |
+
def flow_set(self, flows: Sequence[flow.Flow], attr: str, value: str) -> None:
|
| 133 |
+
"""
|
| 134 |
+
Quickly set a number of common values on flows.
|
| 135 |
+
"""
|
| 136 |
+
val: int | str = value
|
| 137 |
+
if attr == "status_code":
|
| 138 |
+
try:
|
| 139 |
+
val = int(val) # type: ignore
|
| 140 |
+
except ValueError as v:
|
| 141 |
+
raise exceptions.CommandError(
|
| 142 |
+
"Status code is not an integer: %s" % val
|
| 143 |
+
) from v
|
| 144 |
+
|
| 145 |
+
updated = []
|
| 146 |
+
for f in flows:
|
| 147 |
+
req = getattr(f, "request", None)
|
| 148 |
+
rupdate = True
|
| 149 |
+
if req:
|
| 150 |
+
if attr == "method":
|
| 151 |
+
req.method = val
|
| 152 |
+
elif attr == "host":
|
| 153 |
+
req.host = val
|
| 154 |
+
elif attr == "path":
|
| 155 |
+
req.path = val
|
| 156 |
+
elif attr == "url":
|
| 157 |
+
try:
|
| 158 |
+
req.url = val
|
| 159 |
+
except ValueError as e:
|
| 160 |
+
raise exceptions.CommandError(
|
| 161 |
+
f"URL {val!r} is invalid: {e}"
|
| 162 |
+
) from e
|
| 163 |
+
else:
|
| 164 |
+
self.rupdate = False
|
| 165 |
+
|
| 166 |
+
resp = getattr(f, "response", None)
|
| 167 |
+
supdate = True
|
| 168 |
+
if resp:
|
| 169 |
+
if attr == "status_code":
|
| 170 |
+
resp.status_code = val
|
| 171 |
+
if val in status_codes.RESPONSES:
|
| 172 |
+
resp.reason = status_codes.RESPONSES[val] # type: ignore
|
| 173 |
+
elif attr == "reason":
|
| 174 |
+
resp.reason = val
|
| 175 |
+
else:
|
| 176 |
+
supdate = False
|
| 177 |
+
|
| 178 |
+
if rupdate or supdate:
|
| 179 |
+
updated.append(f)
|
| 180 |
+
|
| 181 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 182 |
+
logger.log(ALERT, f"Set {attr} on {len(updated)} flows.")
|
| 183 |
+
|
| 184 |
+
@command.command("flow.decode")
|
| 185 |
+
def decode(self, flows: Sequence[flow.Flow], part: str) -> None:
|
| 186 |
+
"""
|
| 187 |
+
Decode flows.
|
| 188 |
+
"""
|
| 189 |
+
updated = []
|
| 190 |
+
for f in flows:
|
| 191 |
+
p = getattr(f, part, None)
|
| 192 |
+
if p:
|
| 193 |
+
f.backup()
|
| 194 |
+
p.decode()
|
| 195 |
+
updated.append(f)
|
| 196 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 197 |
+
logger.log(ALERT, "Decoded %s flows." % len(updated))
|
| 198 |
+
|
| 199 |
+
@command.command("flow.encode.toggle")
|
| 200 |
+
def encode_toggle(self, flows: Sequence[flow.Flow], part: str) -> None:
|
| 201 |
+
"""
|
| 202 |
+
Toggle flow encoding on and off, using deflate for encoding.
|
| 203 |
+
"""
|
| 204 |
+
updated = []
|
| 205 |
+
for f in flows:
|
| 206 |
+
p = getattr(f, part, None)
|
| 207 |
+
if p:
|
| 208 |
+
f.backup()
|
| 209 |
+
current_enc = p.headers.get("content-encoding", "identity")
|
| 210 |
+
if current_enc == "identity":
|
| 211 |
+
p.encode("deflate")
|
| 212 |
+
else:
|
| 213 |
+
p.decode()
|
| 214 |
+
updated.append(f)
|
| 215 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 216 |
+
logger.log(ALERT, "Toggled encoding on %s flows." % len(updated))
|
| 217 |
+
|
| 218 |
+
@command.command("flow.encode")
|
| 219 |
+
@command.argument("encoding", type=mitmproxy.types.Choice("flow.encode.options"))
|
| 220 |
+
def encode(
|
| 221 |
+
self,
|
| 222 |
+
flows: Sequence[flow.Flow],
|
| 223 |
+
part: str,
|
| 224 |
+
encoding: str,
|
| 225 |
+
) -> None:
|
| 226 |
+
"""
|
| 227 |
+
Encode flows with a specified encoding.
|
| 228 |
+
"""
|
| 229 |
+
updated = []
|
| 230 |
+
for f in flows:
|
| 231 |
+
p = getattr(f, part, None)
|
| 232 |
+
if p:
|
| 233 |
+
current_enc = p.headers.get("content-encoding", "identity")
|
| 234 |
+
if current_enc == "identity":
|
| 235 |
+
f.backup()
|
| 236 |
+
p.encode(encoding)
|
| 237 |
+
updated.append(f)
|
| 238 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 239 |
+
logger.log(ALERT, "Encoded %s flows." % len(updated))
|
| 240 |
+
|
| 241 |
+
@command.command("flow.encode.options")
|
| 242 |
+
def encode_options(self) -> Sequence[str]:
|
| 243 |
+
"""
|
| 244 |
+
The possible values for an encoding specification.
|
| 245 |
+
"""
|
| 246 |
+
return ["gzip", "deflate", "br", "zstd"]
|
| 247 |
+
|
| 248 |
+
@command.command("options.load")
|
| 249 |
+
def options_load(self, path: mitmproxy.types.Path) -> None:
|
| 250 |
+
"""
|
| 251 |
+
Load options from a file.
|
| 252 |
+
"""
|
| 253 |
+
try:
|
| 254 |
+
optmanager.load_paths(ctx.options, path)
|
| 255 |
+
except (OSError, exceptions.OptionsError) as e:
|
| 256 |
+
raise exceptions.CommandError("Could not load options - %s" % e) from e
|
| 257 |
+
|
| 258 |
+
@command.command("options.save")
|
| 259 |
+
def options_save(self, path: mitmproxy.types.Path) -> None:
|
| 260 |
+
"""
|
| 261 |
+
Save options to a file.
|
| 262 |
+
"""
|
| 263 |
+
try:
|
| 264 |
+
optmanager.save(ctx.options, path)
|
| 265 |
+
except OSError as e:
|
| 266 |
+
raise exceptions.CommandError("Could not save options - %s" % e) from e
|
| 267 |
+
|
| 268 |
+
@command.command("options.reset")
|
| 269 |
+
def options_reset(self) -> None:
|
| 270 |
+
"""
|
| 271 |
+
Reset all options to defaults.
|
| 272 |
+
"""
|
| 273 |
+
ctx.options.reset()
|
| 274 |
+
|
| 275 |
+
@command.command("options.reset.one")
|
| 276 |
+
def options_reset_one(self, name: str) -> None:
|
| 277 |
+
"""
|
| 278 |
+
Reset one option to its default value.
|
| 279 |
+
"""
|
| 280 |
+
if name not in ctx.options:
|
| 281 |
+
raise exceptions.CommandError("No such option: %s" % name)
|
| 282 |
+
setattr(
|
| 283 |
+
ctx.options,
|
| 284 |
+
name,
|
| 285 |
+
ctx.options.default(name),
|
| 286 |
+
)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/cut.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import io
|
| 3 |
+
import logging
|
| 4 |
+
import os.path
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import pyperclip
|
| 9 |
+
|
| 10 |
+
import mitmproxy.types
|
| 11 |
+
from mitmproxy import certs
|
| 12 |
+
from mitmproxy import command
|
| 13 |
+
from mitmproxy import exceptions
|
| 14 |
+
from mitmproxy import flow
|
| 15 |
+
from mitmproxy import http
|
| 16 |
+
from mitmproxy.log import ALERT
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def headername(spec: str):
|
| 22 |
+
if not (spec.startswith("header[") and spec.endswith("]")):
|
| 23 |
+
raise exceptions.CommandError("Invalid header spec: %s" % spec)
|
| 24 |
+
return spec[len("header[") : -1].strip()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def is_addr(v):
|
| 28 |
+
return isinstance(v, tuple) and len(v) > 1
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def extract(cut: str, f: flow.Flow) -> str | bytes:
|
| 32 |
+
# Hack for https://github.com/mitmproxy/mitmproxy/issues/6721:
|
| 33 |
+
# Make "save body" keybind work for WebSocket flows.
|
| 34 |
+
# Ideally the keybind would be smarter and this here can get removed.
|
| 35 |
+
if (
|
| 36 |
+
isinstance(f, http.HTTPFlow)
|
| 37 |
+
and f.websocket
|
| 38 |
+
and cut in ("request.content", "response.content")
|
| 39 |
+
):
|
| 40 |
+
return f.websocket._get_formatted_messages()
|
| 41 |
+
|
| 42 |
+
path = cut.split(".")
|
| 43 |
+
current: Any = f
|
| 44 |
+
for i, spec in enumerate(path):
|
| 45 |
+
if spec.startswith("_"):
|
| 46 |
+
raise exceptions.CommandError("Can't access internal attribute %s" % spec)
|
| 47 |
+
|
| 48 |
+
part = getattr(current, spec, None)
|
| 49 |
+
if i == len(path) - 1:
|
| 50 |
+
if spec == "port" and is_addr(current):
|
| 51 |
+
return str(current[1])
|
| 52 |
+
if spec == "host" and is_addr(current):
|
| 53 |
+
return str(current[0])
|
| 54 |
+
elif spec.startswith("header["):
|
| 55 |
+
if not current:
|
| 56 |
+
return ""
|
| 57 |
+
return current.headers.get(headername(spec), "")
|
| 58 |
+
elif isinstance(part, bytes):
|
| 59 |
+
return part
|
| 60 |
+
elif isinstance(part, bool):
|
| 61 |
+
return "true" if part else "false"
|
| 62 |
+
elif isinstance(part, certs.Cert): # pragma: no cover
|
| 63 |
+
return part.to_pem().decode("ascii")
|
| 64 |
+
elif (
|
| 65 |
+
isinstance(part, list)
|
| 66 |
+
and len(part) > 0
|
| 67 |
+
and isinstance(part[0], certs.Cert)
|
| 68 |
+
):
|
| 69 |
+
# TODO: currently this extracts only the very first cert as PEM-encoded string.
|
| 70 |
+
return part[0].to_pem().decode("ascii")
|
| 71 |
+
current = part
|
| 72 |
+
return str(current or "")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def extract_str(cut: str, f: flow.Flow) -> str:
|
| 76 |
+
ret = extract(cut, f)
|
| 77 |
+
if isinstance(ret, bytes):
|
| 78 |
+
return repr(ret)
|
| 79 |
+
else:
|
| 80 |
+
return ret
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class Cut:
|
| 84 |
+
@command.command("cut")
|
| 85 |
+
def cut(
|
| 86 |
+
self,
|
| 87 |
+
flows: Sequence[flow.Flow],
|
| 88 |
+
cuts: mitmproxy.types.CutSpec,
|
| 89 |
+
) -> mitmproxy.types.Data:
|
| 90 |
+
"""
|
| 91 |
+
Cut data from a set of flows. Cut specifications are attribute paths
|
| 92 |
+
from the base of the flow object, with a few conveniences - "port"
|
| 93 |
+
and "host" retrieve parts of an address tuple, ".header[key]"
|
| 94 |
+
retrieves a header value. Return values converted to strings or
|
| 95 |
+
bytes: SSL certificates are converted to PEM format, bools are "true"
|
| 96 |
+
or "false", "bytes" are preserved, and all other values are
|
| 97 |
+
converted to strings.
|
| 98 |
+
"""
|
| 99 |
+
ret: list[list[str | bytes]] = []
|
| 100 |
+
for f in flows:
|
| 101 |
+
ret.append([extract(c, f) for c in cuts])
|
| 102 |
+
return ret # type: ignore
|
| 103 |
+
|
| 104 |
+
@command.command("cut.save")
|
| 105 |
+
def save(
|
| 106 |
+
self,
|
| 107 |
+
flows: Sequence[flow.Flow],
|
| 108 |
+
cuts: mitmproxy.types.CutSpec,
|
| 109 |
+
path: mitmproxy.types.Path,
|
| 110 |
+
) -> None:
|
| 111 |
+
"""
|
| 112 |
+
Save cuts to file. If there are multiple flows or cuts, the format
|
| 113 |
+
is UTF-8 encoded CSV. If there is exactly one row and one column,
|
| 114 |
+
the data is written to file as-is, with raw bytes preserved. If the
|
| 115 |
+
path is prefixed with a "+", values are appended if there is an
|
| 116 |
+
existing file.
|
| 117 |
+
"""
|
| 118 |
+
append = False
|
| 119 |
+
if path.startswith("+"):
|
| 120 |
+
append = True
|
| 121 |
+
epath = os.path.expanduser(path[1:])
|
| 122 |
+
path = mitmproxy.types.Path(epath)
|
| 123 |
+
try:
|
| 124 |
+
if len(cuts) == 1 and len(flows) == 1:
|
| 125 |
+
with open(path, "ab" if append else "wb") as fp:
|
| 126 |
+
if fp.tell() > 0:
|
| 127 |
+
# We're appending to a file that already exists and has content
|
| 128 |
+
fp.write(b"\n")
|
| 129 |
+
v = extract(cuts[0], flows[0])
|
| 130 |
+
if isinstance(v, bytes):
|
| 131 |
+
fp.write(v)
|
| 132 |
+
else:
|
| 133 |
+
fp.write(v.encode("utf8"))
|
| 134 |
+
logger.log(ALERT, "Saved single cut.")
|
| 135 |
+
else:
|
| 136 |
+
with open(
|
| 137 |
+
path, "a" if append else "w", newline="", encoding="utf8"
|
| 138 |
+
) as tfp:
|
| 139 |
+
writer = csv.writer(tfp)
|
| 140 |
+
for f in flows:
|
| 141 |
+
vals = [extract_str(c, f) for c in cuts]
|
| 142 |
+
writer.writerow(vals)
|
| 143 |
+
logger.log(
|
| 144 |
+
ALERT,
|
| 145 |
+
"Saved %s cuts over %d flows as CSV." % (len(cuts), len(flows)),
|
| 146 |
+
)
|
| 147 |
+
except OSError as e:
|
| 148 |
+
logger.error(str(e))
|
| 149 |
+
|
| 150 |
+
@command.command("cut.clip")
|
| 151 |
+
def clip(
|
| 152 |
+
self,
|
| 153 |
+
flows: Sequence[flow.Flow],
|
| 154 |
+
cuts: mitmproxy.types.CutSpec,
|
| 155 |
+
) -> None:
|
| 156 |
+
"""
|
| 157 |
+
Send cuts to the clipboard. If there are multiple flows or cuts, the
|
| 158 |
+
format is UTF-8 encoded CSV. If there is exactly one row and one
|
| 159 |
+
column, the data is written to file as-is, with raw bytes preserved.
|
| 160 |
+
"""
|
| 161 |
+
v: str | bytes
|
| 162 |
+
fp = io.StringIO(newline="")
|
| 163 |
+
if len(cuts) == 1 and len(flows) == 1:
|
| 164 |
+
v = extract_str(cuts[0], flows[0])
|
| 165 |
+
fp.write(v)
|
| 166 |
+
logger.log(ALERT, "Clipped single cut.")
|
| 167 |
+
else:
|
| 168 |
+
writer = csv.writer(fp)
|
| 169 |
+
for f in flows:
|
| 170 |
+
vals = [extract_str(c, f) for c in cuts]
|
| 171 |
+
writer.writerow(vals)
|
| 172 |
+
logger.log(ALERT, "Clipped %s cuts as CSV." % len(cuts))
|
| 173 |
+
try:
|
| 174 |
+
pyperclip.copy(fp.getvalue())
|
| 175 |
+
except pyperclip.PyperclipException as e:
|
| 176 |
+
logger.error(str(e))
|
python/user_packages/Python313/site-packages/mitmproxy/addons/disable_h2c.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class DisableH2C:
|
| 5 |
+
"""
|
| 6 |
+
We currently only support HTTP/2 over a TLS connection.
|
| 7 |
+
|
| 8 |
+
Some clients try to upgrade a connection from HTTP/1.1 to h2c. We need to
|
| 9 |
+
remove those headers to avoid protocol errors if one endpoints suddenly
|
| 10 |
+
starts sending HTTP/2 frames.
|
| 11 |
+
|
| 12 |
+
Some clients might use HTTP/2 Prior Knowledge to directly initiate a session
|
| 13 |
+
by sending the connection preface. We just kill those flows.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def process_flow(self, f):
|
| 17 |
+
if f.request.headers.get("upgrade", "") == "h2c":
|
| 18 |
+
logging.warning(
|
| 19 |
+
"HTTP/2 cleartext connections (h2c upgrade requests) are currently not supported."
|
| 20 |
+
)
|
| 21 |
+
del f.request.headers["upgrade"]
|
| 22 |
+
if "connection" in f.request.headers:
|
| 23 |
+
del f.request.headers["connection"]
|
| 24 |
+
if "http2-settings" in f.request.headers:
|
| 25 |
+
del f.request.headers["http2-settings"]
|
| 26 |
+
|
| 27 |
+
is_connection_preface = (
|
| 28 |
+
f.request.method == "PRI"
|
| 29 |
+
and f.request.path == "*"
|
| 30 |
+
and f.request.http_version == "HTTP/2.0"
|
| 31 |
+
)
|
| 32 |
+
if is_connection_preface:
|
| 33 |
+
if f.killable:
|
| 34 |
+
f.kill()
|
| 35 |
+
logging.warning(
|
| 36 |
+
"Initiating HTTP/2 connections with prior knowledge are currently not supported."
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# Handlers
|
| 40 |
+
|
| 41 |
+
def request(self, f):
|
| 42 |
+
self.process_flow(f)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/dns_resolver.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import ipaddress
|
| 5 |
+
import logging
|
| 6 |
+
import socket
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
from functools import cache
|
| 9 |
+
from typing import Protocol
|
| 10 |
+
|
| 11 |
+
import mitmproxy_rs
|
| 12 |
+
from mitmproxy import ctx
|
| 13 |
+
from mitmproxy import dns
|
| 14 |
+
from mitmproxy.flow import Error
|
| 15 |
+
from mitmproxy.proxy import mode_specs
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DnsResolver:
|
| 21 |
+
def load(self, loader):
|
| 22 |
+
loader.add_option(
|
| 23 |
+
"dns_use_hosts_file",
|
| 24 |
+
bool,
|
| 25 |
+
True,
|
| 26 |
+
"Use the hosts file for DNS lookups in regular DNS mode/wireguard mode.",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
loader.add_option(
|
| 30 |
+
"dns_name_servers",
|
| 31 |
+
Sequence[str],
|
| 32 |
+
[],
|
| 33 |
+
"Name servers to use for lookups in regular DNS mode/wireguard mode. Default: operating system's name servers",
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def configure(self, updated):
|
| 37 |
+
if "dns_use_hosts_file" in updated or "dns_name_servers" in updated:
|
| 38 |
+
self.resolver.cache_clear()
|
| 39 |
+
self.name_servers.cache_clear()
|
| 40 |
+
|
| 41 |
+
@cache
|
| 42 |
+
def name_servers(self) -> list[str]:
|
| 43 |
+
"""
|
| 44 |
+
Returns the operating system's name servers unless custom name servers are set.
|
| 45 |
+
On error, an empty list is returned.
|
| 46 |
+
"""
|
| 47 |
+
try:
|
| 48 |
+
return (
|
| 49 |
+
ctx.options.dns_name_servers
|
| 50 |
+
or mitmproxy_rs.dns.get_system_dns_servers()
|
| 51 |
+
)
|
| 52 |
+
except RuntimeError as e:
|
| 53 |
+
logger.warning(
|
| 54 |
+
f"Failed to get system dns servers: {e}\n"
|
| 55 |
+
f"The dns_name_servers option needs to be set manually."
|
| 56 |
+
)
|
| 57 |
+
return []
|
| 58 |
+
|
| 59 |
+
@cache
|
| 60 |
+
def resolver(self) -> Resolver:
|
| 61 |
+
"""
|
| 62 |
+
Returns:
|
| 63 |
+
The DNS resolver to use.
|
| 64 |
+
Raises:
|
| 65 |
+
MissingNameServers, if name servers are unknown and `dns_use_hosts_file` is disabled.
|
| 66 |
+
"""
|
| 67 |
+
if ns := self.name_servers():
|
| 68 |
+
# We always want to use our own resolver if name server info is available.
|
| 69 |
+
return mitmproxy_rs.dns.DnsResolver(
|
| 70 |
+
name_servers=ns,
|
| 71 |
+
use_hosts_file=ctx.options.dns_use_hosts_file,
|
| 72 |
+
)
|
| 73 |
+
elif ctx.options.dns_use_hosts_file:
|
| 74 |
+
# Fallback to getaddrinfo as hickory's resolver isn't as reliable
|
| 75 |
+
# as we would like it to be (https://github.com/mitmproxy/mitmproxy/issues/7064).
|
| 76 |
+
return GetaddrinfoFallbackResolver()
|
| 77 |
+
else:
|
| 78 |
+
raise MissingNameServers()
|
| 79 |
+
|
| 80 |
+
async def dns_request(self, flow: dns.DNSFlow) -> None:
|
| 81 |
+
if self._should_resolve(flow):
|
| 82 |
+
all_ip_lookups = (
|
| 83 |
+
flow.request.query
|
| 84 |
+
and flow.request.op_code == dns.op_codes.QUERY
|
| 85 |
+
and flow.request.question
|
| 86 |
+
and flow.request.question.class_ == dns.classes.IN
|
| 87 |
+
and flow.request.question.type in (dns.types.A, dns.types.AAAA)
|
| 88 |
+
)
|
| 89 |
+
if all_ip_lookups:
|
| 90 |
+
try:
|
| 91 |
+
flow.response = await self.resolve(flow.request)
|
| 92 |
+
except MissingNameServers:
|
| 93 |
+
flow.error = Error("Cannot resolve, dns_name_servers unknown.")
|
| 94 |
+
elif name_servers := self.name_servers():
|
| 95 |
+
# For other records, the best we can do is to forward the query
|
| 96 |
+
# to an upstream server.
|
| 97 |
+
flow.server_conn.address = (name_servers[0], 53)
|
| 98 |
+
else:
|
| 99 |
+
flow.error = Error("Cannot resolve, dns_name_servers unknown.")
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def _should_resolve(flow: dns.DNSFlow) -> bool:
|
| 103 |
+
return (
|
| 104 |
+
(
|
| 105 |
+
isinstance(flow.client_conn.proxy_mode, mode_specs.DnsMode)
|
| 106 |
+
or (
|
| 107 |
+
isinstance(flow.client_conn.proxy_mode, mode_specs.WireGuardMode)
|
| 108 |
+
and flow.server_conn.address == ("10.0.0.53", 53)
|
| 109 |
+
)
|
| 110 |
+
)
|
| 111 |
+
and flow.live
|
| 112 |
+
and not flow.response
|
| 113 |
+
and not flow.error
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
async def resolve(
|
| 117 |
+
self,
|
| 118 |
+
message: dns.DNSMessage,
|
| 119 |
+
) -> dns.DNSMessage:
|
| 120 |
+
q = message.question
|
| 121 |
+
assert q
|
| 122 |
+
try:
|
| 123 |
+
if q.type == dns.types.A:
|
| 124 |
+
ip_addrs = await self.resolver().lookup_ipv4(q.name)
|
| 125 |
+
else:
|
| 126 |
+
ip_addrs = await self.resolver().lookup_ipv6(q.name)
|
| 127 |
+
except socket.gaierror as e:
|
| 128 |
+
match e.args[0]:
|
| 129 |
+
case socket.EAI_NONAME:
|
| 130 |
+
return message.fail(dns.response_codes.NXDOMAIN)
|
| 131 |
+
case socket.EAI_NODATA:
|
| 132 |
+
ip_addrs = []
|
| 133 |
+
case _:
|
| 134 |
+
return message.fail(dns.response_codes.SERVFAIL)
|
| 135 |
+
|
| 136 |
+
return message.succeed(
|
| 137 |
+
[
|
| 138 |
+
dns.ResourceRecord(
|
| 139 |
+
name=q.name,
|
| 140 |
+
type=q.type,
|
| 141 |
+
class_=q.class_,
|
| 142 |
+
ttl=dns.ResourceRecord.DEFAULT_TTL,
|
| 143 |
+
data=ipaddress.ip_address(ip).packed,
|
| 144 |
+
)
|
| 145 |
+
for ip in ip_addrs
|
| 146 |
+
]
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Resolver(Protocol):
|
| 151 |
+
async def lookup_ip(self, domain: str) -> list[str]: # pragma: no cover
|
| 152 |
+
...
|
| 153 |
+
|
| 154 |
+
async def lookup_ipv4(self, domain: str) -> list[str]: # pragma: no cover
|
| 155 |
+
...
|
| 156 |
+
|
| 157 |
+
async def lookup_ipv6(self, domain: str) -> list[str]: # pragma: no cover
|
| 158 |
+
...
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class GetaddrinfoFallbackResolver(Resolver):
|
| 162 |
+
async def lookup_ip(self, domain: str) -> list[str]:
|
| 163 |
+
return await self._lookup(domain, socket.AF_UNSPEC)
|
| 164 |
+
|
| 165 |
+
async def lookup_ipv4(self, domain: str) -> list[str]:
|
| 166 |
+
return await self._lookup(domain, socket.AF_INET)
|
| 167 |
+
|
| 168 |
+
async def lookup_ipv6(self, domain: str) -> list[str]:
|
| 169 |
+
return await self._lookup(domain, socket.AF_INET6)
|
| 170 |
+
|
| 171 |
+
async def _lookup(self, domain: str, family: socket.AddressFamily) -> list[str]:
|
| 172 |
+
addrinfos = await asyncio.get_running_loop().getaddrinfo(
|
| 173 |
+
host=domain,
|
| 174 |
+
port=None,
|
| 175 |
+
family=family,
|
| 176 |
+
type=socket.SOCK_STREAM,
|
| 177 |
+
)
|
| 178 |
+
return [addrinfo[4][0] for addrinfo in addrinfos]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class MissingNameServers(RuntimeError):
|
| 182 |
+
pass
|
python/user_packages/Python313/site-packages/mitmproxy/addons/dumper.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import shutil
|
| 4 |
+
import sys
|
| 5 |
+
from typing import IO
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
from wsproto.frame_protocol import CloseReason
|
| 9 |
+
|
| 10 |
+
import mitmproxy_rs
|
| 11 |
+
from mitmproxy import contentviews
|
| 12 |
+
from mitmproxy import ctx
|
| 13 |
+
from mitmproxy import dns
|
| 14 |
+
from mitmproxy import exceptions
|
| 15 |
+
from mitmproxy import flow
|
| 16 |
+
from mitmproxy import flowfilter
|
| 17 |
+
from mitmproxy import http
|
| 18 |
+
from mitmproxy.contrib import click as miniclick
|
| 19 |
+
from mitmproxy.net.dns import response_codes
|
| 20 |
+
from mitmproxy.options import CONTENT_VIEW_LINES_CUTOFF
|
| 21 |
+
from mitmproxy.tcp import TCPFlow
|
| 22 |
+
from mitmproxy.tcp import TCPMessage
|
| 23 |
+
from mitmproxy.udp import UDPFlow
|
| 24 |
+
from mitmproxy.udp import UDPMessage
|
| 25 |
+
from mitmproxy.utils import human
|
| 26 |
+
from mitmproxy.utils import strutils
|
| 27 |
+
from mitmproxy.utils import vt_codes
|
| 28 |
+
from mitmproxy.websocket import WebSocketData
|
| 29 |
+
from mitmproxy.websocket import WebSocketMessage
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def indent(n: int, text: str) -> str:
|
| 33 |
+
lines = str(text).strip().splitlines()
|
| 34 |
+
pad = " " * n
|
| 35 |
+
return "\n".join(pad + i for i in lines)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
CONTENTVIEW_STYLES: dict[str, dict[str, str | bool]] = {
|
| 39 |
+
"name": dict(fg="yellow"),
|
| 40 |
+
"string": dict(fg="green"),
|
| 41 |
+
"number": dict(fg="blue"),
|
| 42 |
+
"boolean": dict(fg="magenta"),
|
| 43 |
+
"comment": dict(dim=True),
|
| 44 |
+
"error": dict(fg="red"),
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Dumper:
|
| 49 |
+
def __init__(self, outfile: IO[str] | None = None):
|
| 50 |
+
self.filter: flowfilter.TFilter | None = None
|
| 51 |
+
self.outfp: IO[str] = outfile or sys.stdout
|
| 52 |
+
self.out_has_vt_codes = vt_codes.ensure_supported(self.outfp)
|
| 53 |
+
|
| 54 |
+
def load(self, loader):
|
| 55 |
+
loader.add_option(
|
| 56 |
+
"flow_detail",
|
| 57 |
+
int,
|
| 58 |
+
1,
|
| 59 |
+
f"""
|
| 60 |
+
The display detail level for flows in mitmdump: 0 (quiet) to 4 (very verbose).
|
| 61 |
+
0: no output
|
| 62 |
+
1: shortened request URL with response status code
|
| 63 |
+
2: full request URL with response status code and HTTP headers
|
| 64 |
+
3: 2 + truncated response content, content of WebSocket and TCP messages (content_view_lines_cutoff: {CONTENT_VIEW_LINES_CUTOFF})
|
| 65 |
+
4: 3 + nothing is truncated
|
| 66 |
+
""",
|
| 67 |
+
)
|
| 68 |
+
loader.add_option(
|
| 69 |
+
"dumper_default_contentview",
|
| 70 |
+
str,
|
| 71 |
+
"auto",
|
| 72 |
+
"The default content view mode.",
|
| 73 |
+
choices=contentviews.registry.available_views(),
|
| 74 |
+
)
|
| 75 |
+
loader.add_option(
|
| 76 |
+
"dumper_filter", Optional[str], None, "Limit which flows are dumped."
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def configure(self, updated):
|
| 80 |
+
if "dumper_filter" in updated:
|
| 81 |
+
if ctx.options.dumper_filter:
|
| 82 |
+
try:
|
| 83 |
+
self.filter = flowfilter.parse(ctx.options.dumper_filter)
|
| 84 |
+
except ValueError as e:
|
| 85 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 86 |
+
else:
|
| 87 |
+
self.filter = None
|
| 88 |
+
|
| 89 |
+
def style(self, text: str, **style) -> str:
|
| 90 |
+
if style and self.out_has_vt_codes:
|
| 91 |
+
text = miniclick.style(text, **style)
|
| 92 |
+
return text
|
| 93 |
+
|
| 94 |
+
def echo(self, text: str, ident=None, **style):
|
| 95 |
+
if ident:
|
| 96 |
+
text = indent(ident, text)
|
| 97 |
+
text = self.style(text, **style)
|
| 98 |
+
print(text, file=self.outfp)
|
| 99 |
+
|
| 100 |
+
def _echo_headers(self, headers: http.Headers):
|
| 101 |
+
for k, v in headers.fields:
|
| 102 |
+
ks = strutils.bytes_to_escaped_str(k)
|
| 103 |
+
ks = self.style(ks, fg="blue")
|
| 104 |
+
vs = strutils.bytes_to_escaped_str(v)
|
| 105 |
+
self.echo(f"{ks}: {vs}", ident=4)
|
| 106 |
+
|
| 107 |
+
def _echo_trailers(self, trailers: http.Headers | None):
|
| 108 |
+
if not trailers:
|
| 109 |
+
return
|
| 110 |
+
self.echo("--- HTTP Trailers", fg="magenta", ident=4)
|
| 111 |
+
self._echo_headers(trailers)
|
| 112 |
+
|
| 113 |
+
def _echo_message(
|
| 114 |
+
self,
|
| 115 |
+
message: http.Message | TCPMessage | UDPMessage | WebSocketMessage,
|
| 116 |
+
flow: http.HTTPFlow | TCPFlow | UDPFlow,
|
| 117 |
+
):
|
| 118 |
+
pretty = contentviews.prettify_message(
|
| 119 |
+
message,
|
| 120 |
+
flow,
|
| 121 |
+
ctx.options.dumper_default_contentview,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
if ctx.options.flow_detail == 3:
|
| 125 |
+
content_to_echo = strutils.cut_after_n_lines(
|
| 126 |
+
pretty.text, ctx.options.content_view_lines_cutoff
|
| 127 |
+
)
|
| 128 |
+
else:
|
| 129 |
+
content_to_echo = pretty.text
|
| 130 |
+
|
| 131 |
+
if content_to_echo:
|
| 132 |
+
highlighted = mitmproxy_rs.syntax_highlight.highlight(
|
| 133 |
+
pretty.text, pretty.syntax_highlight
|
| 134 |
+
)
|
| 135 |
+
self.echo("")
|
| 136 |
+
self.echo(
|
| 137 |
+
"".join(
|
| 138 |
+
self.style(chunk, **CONTENTVIEW_STYLES.get(tag, {}))
|
| 139 |
+
for tag, chunk in highlighted
|
| 140 |
+
),
|
| 141 |
+
ident=4,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if len(content_to_echo) < len(pretty.text):
|
| 145 |
+
self.echo("(cut off)", ident=4, dim=True)
|
| 146 |
+
|
| 147 |
+
if ctx.options.flow_detail >= 2:
|
| 148 |
+
self.echo("")
|
| 149 |
+
|
| 150 |
+
def _fmt_client(self, flow: flow.Flow) -> str:
|
| 151 |
+
if flow.is_replay == "request":
|
| 152 |
+
return self.style("[replay]", fg="yellow", bold=True)
|
| 153 |
+
elif flow.client_conn.peername:
|
| 154 |
+
return self.style(
|
| 155 |
+
strutils.escape_control_characters(
|
| 156 |
+
human.format_address(flow.client_conn.peername)
|
| 157 |
+
)
|
| 158 |
+
)
|
| 159 |
+
else: # pragma: no cover
|
| 160 |
+
# this should not happen, but we're defensive here.
|
| 161 |
+
return ""
|
| 162 |
+
|
| 163 |
+
def _echo_request_line(self, flow: http.HTTPFlow) -> None:
|
| 164 |
+
client = self._fmt_client(flow)
|
| 165 |
+
|
| 166 |
+
pushed = " PUSH_PROMISE" if "h2-pushed-stream" in flow.metadata else ""
|
| 167 |
+
method = flow.request.method + pushed
|
| 168 |
+
method_color = dict(GET="green", DELETE="red").get(method.upper(), "magenta")
|
| 169 |
+
method = self.style(
|
| 170 |
+
strutils.escape_control_characters(method), fg=method_color, bold=True
|
| 171 |
+
)
|
| 172 |
+
if ctx.options.showhost:
|
| 173 |
+
url = flow.request.pretty_url
|
| 174 |
+
else:
|
| 175 |
+
url = flow.request.url
|
| 176 |
+
|
| 177 |
+
if ctx.options.flow_detail == 1:
|
| 178 |
+
# We need to truncate before applying styles, so we just focus on the URL.
|
| 179 |
+
terminal_width_limit = max(shutil.get_terminal_size()[0] - 25, 50)
|
| 180 |
+
if len(url) > terminal_width_limit:
|
| 181 |
+
url = url[:terminal_width_limit] + "…"
|
| 182 |
+
url = self.style(strutils.escape_control_characters(url), bold=True)
|
| 183 |
+
|
| 184 |
+
http_version = ""
|
| 185 |
+
if not (
|
| 186 |
+
flow.request.is_http10 or flow.request.is_http11
|
| 187 |
+
) or flow.request.http_version != getattr(
|
| 188 |
+
flow.response, "http_version", "HTTP/1.1"
|
| 189 |
+
):
|
| 190 |
+
# Hide version for h1 <-> h1 connections.
|
| 191 |
+
http_version = " " + flow.request.http_version
|
| 192 |
+
|
| 193 |
+
self.echo(f"{client}: {method} {url}{http_version}")
|
| 194 |
+
|
| 195 |
+
def _echo_response_line(self, flow: http.HTTPFlow) -> None:
|
| 196 |
+
if flow.is_replay == "response":
|
| 197 |
+
replay_str = "[replay]"
|
| 198 |
+
replay = self.style(replay_str, fg="yellow", bold=True)
|
| 199 |
+
else:
|
| 200 |
+
replay_str = ""
|
| 201 |
+
replay = ""
|
| 202 |
+
|
| 203 |
+
assert flow.response
|
| 204 |
+
code_int = flow.response.status_code
|
| 205 |
+
code_color = None
|
| 206 |
+
if 200 <= code_int < 300:
|
| 207 |
+
code_color = "green"
|
| 208 |
+
elif 300 <= code_int < 400:
|
| 209 |
+
code_color = "magenta"
|
| 210 |
+
elif 400 <= code_int < 600:
|
| 211 |
+
code_color = "red"
|
| 212 |
+
code = self.style(
|
| 213 |
+
str(code_int),
|
| 214 |
+
fg=code_color,
|
| 215 |
+
bold=True,
|
| 216 |
+
blink=(code_int == 418),
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
if not (flow.response.is_http2 or flow.response.is_http3):
|
| 220 |
+
reason = flow.response.reason
|
| 221 |
+
else:
|
| 222 |
+
reason = http.status_codes.RESPONSES.get(flow.response.status_code, "")
|
| 223 |
+
reason = self.style(
|
| 224 |
+
strutils.escape_control_characters(reason), fg=code_color, bold=True
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
if flow.response.raw_content is None:
|
| 228 |
+
size = "(content missing)"
|
| 229 |
+
else:
|
| 230 |
+
size = human.pretty_size(len(flow.response.raw_content))
|
| 231 |
+
size = self.style(size, bold=True)
|
| 232 |
+
|
| 233 |
+
http_version = ""
|
| 234 |
+
if (
|
| 235 |
+
not (flow.response.is_http10 or flow.response.is_http11)
|
| 236 |
+
or flow.request.http_version != flow.response.http_version
|
| 237 |
+
):
|
| 238 |
+
# Hide version for h1 <-> h1 connections.
|
| 239 |
+
http_version = f"{flow.response.http_version} "
|
| 240 |
+
|
| 241 |
+
arrows = self.style(" <<", bold=True)
|
| 242 |
+
if ctx.options.flow_detail == 1:
|
| 243 |
+
# This aligns the HTTP response code with the HTTP request method:
|
| 244 |
+
# 127.0.0.1:59519: GET http://example.com/
|
| 245 |
+
# << 304 Not Modified 0b
|
| 246 |
+
pad = max(
|
| 247 |
+
0,
|
| 248 |
+
len(human.format_address(flow.client_conn.peername))
|
| 249 |
+
- (2 + len(http_version) + len(replay_str)),
|
| 250 |
+
)
|
| 251 |
+
arrows = " " * pad + arrows
|
| 252 |
+
|
| 253 |
+
self.echo(f"{replay}{arrows} {http_version}{code} {reason} {size}")
|
| 254 |
+
|
| 255 |
+
def echo_flow(self, f: http.HTTPFlow) -> None:
|
| 256 |
+
if f.request:
|
| 257 |
+
self._echo_request_line(f)
|
| 258 |
+
if ctx.options.flow_detail >= 2:
|
| 259 |
+
self._echo_headers(f.request.headers)
|
| 260 |
+
if ctx.options.flow_detail >= 3:
|
| 261 |
+
self._echo_message(f.request, f)
|
| 262 |
+
if ctx.options.flow_detail >= 2:
|
| 263 |
+
self._echo_trailers(f.request.trailers)
|
| 264 |
+
|
| 265 |
+
if f.response:
|
| 266 |
+
self._echo_response_line(f)
|
| 267 |
+
if ctx.options.flow_detail >= 2:
|
| 268 |
+
self._echo_headers(f.response.headers)
|
| 269 |
+
if ctx.options.flow_detail >= 3:
|
| 270 |
+
self._echo_message(f.response, f)
|
| 271 |
+
if ctx.options.flow_detail >= 2:
|
| 272 |
+
self._echo_trailers(f.response.trailers)
|
| 273 |
+
|
| 274 |
+
if f.error:
|
| 275 |
+
msg = strutils.escape_control_characters(f.error.msg)
|
| 276 |
+
self.echo(f" << {msg}", bold=True, fg="red")
|
| 277 |
+
|
| 278 |
+
self.outfp.flush()
|
| 279 |
+
|
| 280 |
+
def match(self, f):
|
| 281 |
+
if ctx.options.flow_detail == 0:
|
| 282 |
+
return False
|
| 283 |
+
if not self.filter:
|
| 284 |
+
return True
|
| 285 |
+
elif flowfilter.match(self.filter, f):
|
| 286 |
+
return True
|
| 287 |
+
return False
|
| 288 |
+
|
| 289 |
+
def response(self, f):
|
| 290 |
+
if self.match(f):
|
| 291 |
+
self.echo_flow(f)
|
| 292 |
+
|
| 293 |
+
def error(self, f):
|
| 294 |
+
if self.match(f):
|
| 295 |
+
self.echo_flow(f)
|
| 296 |
+
|
| 297 |
+
def http_connect_error(self, f):
|
| 298 |
+
if self.match(f):
|
| 299 |
+
self.echo_flow(f)
|
| 300 |
+
|
| 301 |
+
def websocket_message(self, f: http.HTTPFlow):
|
| 302 |
+
assert f.websocket is not None # satisfy type checker
|
| 303 |
+
if self.match(f):
|
| 304 |
+
message = f.websocket.messages[-1]
|
| 305 |
+
|
| 306 |
+
direction = "->" if message.from_client else "<-"
|
| 307 |
+
self.echo(
|
| 308 |
+
f"{human.format_address(f.client_conn.peername)} "
|
| 309 |
+
f"{direction} WebSocket {message.type.name.lower()} message "
|
| 310 |
+
f"{direction} {human.format_address(f.server_conn.address)}{f.request.path}"
|
| 311 |
+
)
|
| 312 |
+
if ctx.options.flow_detail >= 3:
|
| 313 |
+
self._echo_message(message, f)
|
| 314 |
+
|
| 315 |
+
def websocket_end(self, f: http.HTTPFlow):
|
| 316 |
+
assert f.websocket is not None # satisfy type checker
|
| 317 |
+
if self.match(f):
|
| 318 |
+
if f.websocket.close_code in {1000, 1001, 1005}:
|
| 319 |
+
c = "client" if f.websocket.closed_by_client else "server"
|
| 320 |
+
self.echo(
|
| 321 |
+
f"WebSocket connection closed by {c}: {f.websocket.close_code} {f.websocket.close_reason}"
|
| 322 |
+
)
|
| 323 |
+
else:
|
| 324 |
+
error = flow.Error(
|
| 325 |
+
f"WebSocket Error: {self.format_websocket_error(f.websocket)}"
|
| 326 |
+
)
|
| 327 |
+
self.echo(
|
| 328 |
+
f"Error in WebSocket connection to {human.format_address(f.server_conn.address)}: {error}",
|
| 329 |
+
fg="red",
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
def format_websocket_error(self, websocket: WebSocketData) -> str:
|
| 333 |
+
try:
|
| 334 |
+
ret = CloseReason(websocket.close_code).name # type: ignore
|
| 335 |
+
except ValueError:
|
| 336 |
+
ret = f"UNKNOWN_ERROR={websocket.close_code}"
|
| 337 |
+
if websocket.close_reason:
|
| 338 |
+
ret += f" (reason: {websocket.close_reason})"
|
| 339 |
+
return ret
|
| 340 |
+
|
| 341 |
+
def _proto_error(self, f):
|
| 342 |
+
if self.match(f):
|
| 343 |
+
self.echo(
|
| 344 |
+
f"Error in {f.type.upper()} connection to {human.format_address(f.server_conn.address)}: {f.error}",
|
| 345 |
+
fg="red",
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
def tcp_error(self, f):
|
| 349 |
+
self._proto_error(f)
|
| 350 |
+
|
| 351 |
+
def udp_error(self, f):
|
| 352 |
+
self._proto_error(f)
|
| 353 |
+
|
| 354 |
+
def _proto_message(self, f: TCPFlow | UDPFlow) -> None:
|
| 355 |
+
if self.match(f):
|
| 356 |
+
message = f.messages[-1]
|
| 357 |
+
direction = "->" if message.from_client else "<-"
|
| 358 |
+
if f.client_conn.tls_version == "QUICv1":
|
| 359 |
+
if f.type == "tcp":
|
| 360 |
+
quic_type = "stream"
|
| 361 |
+
else:
|
| 362 |
+
quic_type = "dgrams"
|
| 363 |
+
# TODO: This should not be metadata, this should be typed attributes.
|
| 364 |
+
flow_type = (
|
| 365 |
+
f"quic {quic_type} {f.metadata.get('quic_stream_id_client', '')} "
|
| 366 |
+
f"{direction} mitmproxy {direction} "
|
| 367 |
+
f"quic {quic_type} {f.metadata.get('quic_stream_id_server', '')}"
|
| 368 |
+
)
|
| 369 |
+
else:
|
| 370 |
+
flow_type = f.type
|
| 371 |
+
self.echo(
|
| 372 |
+
"{client} {direction} {type} {direction} {server}".format(
|
| 373 |
+
client=human.format_address(f.client_conn.peername),
|
| 374 |
+
server=human.format_address(f.server_conn.address),
|
| 375 |
+
direction=direction,
|
| 376 |
+
type=flow_type,
|
| 377 |
+
)
|
| 378 |
+
)
|
| 379 |
+
if ctx.options.flow_detail >= 3:
|
| 380 |
+
self._echo_message(message, f)
|
| 381 |
+
|
| 382 |
+
def tcp_message(self, f):
|
| 383 |
+
self._proto_message(f)
|
| 384 |
+
|
| 385 |
+
def udp_message(self, f):
|
| 386 |
+
self._proto_message(f)
|
| 387 |
+
|
| 388 |
+
def _echo_dns_query(self, f: dns.DNSFlow) -> None:
|
| 389 |
+
client = self._fmt_client(f)
|
| 390 |
+
opcode = dns.op_codes.to_str(f.request.op_code)
|
| 391 |
+
type = dns.types.to_str(f.request.questions[0].type)
|
| 392 |
+
|
| 393 |
+
desc = f"DNS {opcode} ({type})"
|
| 394 |
+
desc_color = {
|
| 395 |
+
"A": "green",
|
| 396 |
+
"AAAA": "magenta",
|
| 397 |
+
}.get(type, "red")
|
| 398 |
+
desc = self.style(desc, fg=desc_color)
|
| 399 |
+
|
| 400 |
+
name = self.style(f.request.questions[0].name, bold=True)
|
| 401 |
+
self.echo(f"{client}: {desc} {name}")
|
| 402 |
+
|
| 403 |
+
def dns_response(self, f: dns.DNSFlow):
|
| 404 |
+
assert f.response
|
| 405 |
+
if self.match(f):
|
| 406 |
+
self._echo_dns_query(f)
|
| 407 |
+
|
| 408 |
+
arrows = self.style(" <<", bold=True)
|
| 409 |
+
if f.response.answers:
|
| 410 |
+
answers = ", ".join(
|
| 411 |
+
self.style(str(x), fg="bright_blue") for x in f.response.answers
|
| 412 |
+
)
|
| 413 |
+
else:
|
| 414 |
+
answers = self.style(
|
| 415 |
+
response_codes.to_str(
|
| 416 |
+
f.response.response_code,
|
| 417 |
+
),
|
| 418 |
+
fg="red",
|
| 419 |
+
)
|
| 420 |
+
self.echo(f"{arrows} {answers}")
|
| 421 |
+
|
| 422 |
+
def dns_error(self, f: dns.DNSFlow):
|
| 423 |
+
assert f.error
|
| 424 |
+
if self.match(f):
|
| 425 |
+
self._echo_dns_query(f)
|
| 426 |
+
msg = strutils.escape_control_characters(f.error.msg)
|
| 427 |
+
self.echo(f" << {msg}", bold=True, fg="red")
|
python/user_packages/Python313/site-packages/mitmproxy/addons/errorcheck.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from mitmproxy import log
|
| 6 |
+
from mitmproxy.contrib import click as miniclick
|
| 7 |
+
from mitmproxy.utils import vt_codes
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ErrorCheck:
|
| 11 |
+
"""Monitor startup for error log entries, and terminate immediately if there are some."""
|
| 12 |
+
|
| 13 |
+
repeat_errors_on_stderr: bool
|
| 14 |
+
"""
|
| 15 |
+
Repeat all errors on stderr before exiting.
|
| 16 |
+
This is useful for the console UI, which otherwise swallows all output.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, repeat_errors_on_stderr: bool = False) -> None:
|
| 20 |
+
self.repeat_errors_on_stderr = repeat_errors_on_stderr
|
| 21 |
+
|
| 22 |
+
self.logger = ErrorCheckHandler()
|
| 23 |
+
self.logger.install()
|
| 24 |
+
|
| 25 |
+
def finish(self):
|
| 26 |
+
self.logger.uninstall()
|
| 27 |
+
|
| 28 |
+
async def shutdown_if_errored(self):
|
| 29 |
+
# don't run immediately, wait for all logging tasks to finish.
|
| 30 |
+
await asyncio.sleep(0)
|
| 31 |
+
if self.logger.has_errored:
|
| 32 |
+
plural = "s" if len(self.logger.has_errored) > 1 else ""
|
| 33 |
+
if self.repeat_errors_on_stderr:
|
| 34 |
+
message = f"Error{plural} logged during startup:"
|
| 35 |
+
if vt_codes.ensure_supported(sys.stderr): # pragma: no cover
|
| 36 |
+
message = miniclick.style(message, fg="red")
|
| 37 |
+
details = "\n".join(
|
| 38 |
+
self.logger.format(r) for r in self.logger.has_errored
|
| 39 |
+
)
|
| 40 |
+
print(f"{message}\n{details}", file=sys.stderr)
|
| 41 |
+
else:
|
| 42 |
+
print(
|
| 43 |
+
f"Error{plural} logged during startup, exiting...", file=sys.stderr
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
sys.exit(1)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ErrorCheckHandler(log.MitmLogHandler):
|
| 50 |
+
def __init__(self) -> None:
|
| 51 |
+
super().__init__(logging.ERROR)
|
| 52 |
+
self.has_errored: list[logging.LogRecord] = []
|
| 53 |
+
|
| 54 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 55 |
+
self.has_errored.append(record)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/eventstore.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import collections
|
| 3 |
+
import logging
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
|
| 6 |
+
from mitmproxy import command
|
| 7 |
+
from mitmproxy import log
|
| 8 |
+
from mitmproxy.log import LogEntry
|
| 9 |
+
from mitmproxy.utils import signals
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class EventStore:
|
| 13 |
+
def __init__(self, size: int = 10000) -> None:
|
| 14 |
+
self.data: collections.deque[LogEntry] = collections.deque(maxlen=size)
|
| 15 |
+
self.sig_add = signals.SyncSignal(lambda entry: None)
|
| 16 |
+
self.sig_refresh = signals.SyncSignal(lambda: None)
|
| 17 |
+
|
| 18 |
+
self.logger = CallbackLogger(self._add_log)
|
| 19 |
+
self.logger.install()
|
| 20 |
+
|
| 21 |
+
def done(self):
|
| 22 |
+
self.logger.uninstall()
|
| 23 |
+
|
| 24 |
+
def _add_log(self, entry: LogEntry) -> None:
|
| 25 |
+
self.data.append(entry)
|
| 26 |
+
self.sig_add.send(entry)
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def size(self) -> int | None:
|
| 30 |
+
return self.data.maxlen
|
| 31 |
+
|
| 32 |
+
@command.command("eventstore.clear")
|
| 33 |
+
def clear(self) -> None:
|
| 34 |
+
"""
|
| 35 |
+
Clear the event log.
|
| 36 |
+
"""
|
| 37 |
+
self.data.clear()
|
| 38 |
+
self.sig_refresh.send()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CallbackLogger(log.MitmLogHandler):
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
callback: Callable[[LogEntry], None],
|
| 45 |
+
):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.callback = callback
|
| 48 |
+
self.event_loop = asyncio.get_running_loop()
|
| 49 |
+
self.formatter = log.MitmFormatter(colorize=False)
|
| 50 |
+
|
| 51 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 52 |
+
entry = LogEntry(
|
| 53 |
+
msg=self.format(record),
|
| 54 |
+
level=log.LOGGING_LEVELS_TO_LOGENTRY.get(record.levelno, "error"),
|
| 55 |
+
)
|
| 56 |
+
self.event_loop.call_soon_threadsafe(self.callback, entry)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/export.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import shlex
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
|
| 6 |
+
import pyperclip
|
| 7 |
+
|
| 8 |
+
import mitmproxy.types
|
| 9 |
+
from mitmproxy import command
|
| 10 |
+
from mitmproxy import ctx
|
| 11 |
+
from mitmproxy import exceptions
|
| 12 |
+
from mitmproxy import flow
|
| 13 |
+
from mitmproxy import http
|
| 14 |
+
from mitmproxy.net.http.http1 import assemble
|
| 15 |
+
from mitmproxy.utils import strutils
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def cleanup_request(f: flow.Flow) -> http.Request:
|
| 19 |
+
if not getattr(f, "request", None):
|
| 20 |
+
raise exceptions.CommandError("Can't export flow with no request.")
|
| 21 |
+
assert isinstance(f, http.HTTPFlow)
|
| 22 |
+
request = f.request.copy()
|
| 23 |
+
request.decode(strict=False)
|
| 24 |
+
return request
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def pop_headers(request: http.Request) -> None:
|
| 28 |
+
"""Remove some headers that are redundant for curl/httpie export."""
|
| 29 |
+
request.headers.pop("content-length", None)
|
| 30 |
+
|
| 31 |
+
if request.headers.get("host", "") == request.host:
|
| 32 |
+
request.headers.pop("host")
|
| 33 |
+
if request.headers.get(":authority", "") == request.host:
|
| 34 |
+
request.headers.pop(":authority")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def cleanup_response(f: flow.Flow) -> http.Response:
|
| 38 |
+
if not getattr(f, "response", None):
|
| 39 |
+
raise exceptions.CommandError("Can't export flow with no response.")
|
| 40 |
+
assert isinstance(f, http.HTTPFlow)
|
| 41 |
+
response = f.response.copy() # type: ignore
|
| 42 |
+
response.decode(strict=False)
|
| 43 |
+
return response
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def request_content_for_console(request: http.Request) -> str:
|
| 47 |
+
try:
|
| 48 |
+
text = request.get_text(strict=True)
|
| 49 |
+
assert text
|
| 50 |
+
except ValueError:
|
| 51 |
+
# shlex.quote doesn't support a bytes object
|
| 52 |
+
# see https://github.com/python/cpython/pull/10871
|
| 53 |
+
raise exceptions.CommandError("Request content must be valid unicode")
|
| 54 |
+
escape_control_chars = {chr(i): f"\\x{i:02x}" for i in range(32)}
|
| 55 |
+
escaped_text = "".join(escape_control_chars.get(x, x) for x in text)
|
| 56 |
+
if any(char in escape_control_chars for char in text):
|
| 57 |
+
# Escaped chars need to be unescaped by the shell to be properly inperpreted by curl and httpie
|
| 58 |
+
return f'"$(printf {shlex.quote(escaped_text)})"'
|
| 59 |
+
|
| 60 |
+
return shlex.quote(escaped_text)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def curl_command(f: flow.Flow) -> str:
|
| 64 |
+
request = cleanup_request(f)
|
| 65 |
+
pop_headers(request)
|
| 66 |
+
|
| 67 |
+
args = ["curl"]
|
| 68 |
+
|
| 69 |
+
server_addr = f.server_conn.peername[0] if f.server_conn.peername else None
|
| 70 |
+
|
| 71 |
+
if (
|
| 72 |
+
ctx.options.export_preserve_original_ip
|
| 73 |
+
and server_addr
|
| 74 |
+
and request.pretty_host != server_addr
|
| 75 |
+
):
|
| 76 |
+
resolve = f"{request.pretty_host}:{request.port}:[{server_addr}]"
|
| 77 |
+
args.append("--resolve")
|
| 78 |
+
args.append(resolve)
|
| 79 |
+
|
| 80 |
+
for k, v in request.headers.items(multi=True):
|
| 81 |
+
if k.lower() == "accept-encoding":
|
| 82 |
+
args.append("--compressed")
|
| 83 |
+
else:
|
| 84 |
+
args += ["-H", f"{k}: {v}"]
|
| 85 |
+
|
| 86 |
+
if request.method != "GET":
|
| 87 |
+
if not request.content:
|
| 88 |
+
# curl will not calculate content-length if there is no content
|
| 89 |
+
# some server/verb combinations require content-length headers
|
| 90 |
+
# (ex. nginx and POST)
|
| 91 |
+
args += ["-H", "content-length: 0"]
|
| 92 |
+
|
| 93 |
+
args += ["-X", request.method]
|
| 94 |
+
|
| 95 |
+
args.append(request.pretty_url)
|
| 96 |
+
|
| 97 |
+
command = " ".join(shlex.quote(arg) for arg in args)
|
| 98 |
+
if request.content:
|
| 99 |
+
command += f" -d {request_content_for_console(request)}"
|
| 100 |
+
return command
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def httpie_command(f: flow.Flow) -> str:
|
| 104 |
+
request = cleanup_request(f)
|
| 105 |
+
pop_headers(request)
|
| 106 |
+
|
| 107 |
+
# TODO: Once https://github.com/httpie/httpie/issues/414 is implemented, we
|
| 108 |
+
# should ensure we always connect to the IP address specified in the flow,
|
| 109 |
+
# similar to how it's done in curl_command.
|
| 110 |
+
url = request.pretty_url
|
| 111 |
+
|
| 112 |
+
args = ["http", request.method, url]
|
| 113 |
+
for k, v in request.headers.items(multi=True):
|
| 114 |
+
args.append(f"{k}: {v}")
|
| 115 |
+
cmd = " ".join(shlex.quote(arg) for arg in args)
|
| 116 |
+
if request.content:
|
| 117 |
+
cmd += " <<< " + request_content_for_console(request)
|
| 118 |
+
return cmd
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def raw_request(f: flow.Flow) -> bytes:
|
| 122 |
+
request = cleanup_request(f)
|
| 123 |
+
if request.raw_content is None:
|
| 124 |
+
raise exceptions.CommandError("Request content missing.")
|
| 125 |
+
return assemble.assemble_request(request)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def raw_response(f: flow.Flow) -> bytes:
|
| 129 |
+
response = cleanup_response(f)
|
| 130 |
+
if response.raw_content is None:
|
| 131 |
+
raise exceptions.CommandError("Response content missing.")
|
| 132 |
+
return assemble.assemble_response(response)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def raw(f: flow.Flow, separator=b"\r\n\r\n") -> bytes:
|
| 136 |
+
"""Return either the request or response if only one exists, otherwise return both"""
|
| 137 |
+
request_present = (
|
| 138 |
+
isinstance(f, http.HTTPFlow) and f.request and f.request.raw_content is not None
|
| 139 |
+
)
|
| 140 |
+
response_present = (
|
| 141 |
+
isinstance(f, http.HTTPFlow)
|
| 142 |
+
and f.response
|
| 143 |
+
and f.response.raw_content is not None
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
if request_present and response_present:
|
| 147 |
+
parts = [raw_request(f), raw_response(f)]
|
| 148 |
+
if isinstance(f, http.HTTPFlow) and f.websocket:
|
| 149 |
+
parts.append(f.websocket._get_formatted_messages())
|
| 150 |
+
return separator.join(parts)
|
| 151 |
+
elif request_present:
|
| 152 |
+
return raw_request(f)
|
| 153 |
+
elif response_present:
|
| 154 |
+
return raw_response(f)
|
| 155 |
+
else:
|
| 156 |
+
raise exceptions.CommandError("Can't export flow with no request or response.")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
formats: dict[str, Callable[[flow.Flow], str | bytes]] = dict(
|
| 160 |
+
curl=curl_command,
|
| 161 |
+
httpie=httpie_command,
|
| 162 |
+
raw=raw,
|
| 163 |
+
raw_request=raw_request,
|
| 164 |
+
raw_response=raw_response,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class Export:
|
| 169 |
+
def load(self, loader):
|
| 170 |
+
loader.add_option(
|
| 171 |
+
"export_preserve_original_ip",
|
| 172 |
+
bool,
|
| 173 |
+
False,
|
| 174 |
+
"""
|
| 175 |
+
When exporting a request as an external command, make an effort to
|
| 176 |
+
connect to the same IP as in the original request. This helps with
|
| 177 |
+
reproducibility in cases where the behaviour depends on the
|
| 178 |
+
particular host we are connecting to. Currently this only affects
|
| 179 |
+
curl exports.
|
| 180 |
+
""",
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
@command.command("export.formats")
|
| 184 |
+
def formats(self) -> Sequence[str]:
|
| 185 |
+
"""
|
| 186 |
+
Return a list of the supported export formats.
|
| 187 |
+
"""
|
| 188 |
+
return list(sorted(formats.keys()))
|
| 189 |
+
|
| 190 |
+
@command.command("export.file")
|
| 191 |
+
def file(self, format: str, flow: flow.Flow, path: mitmproxy.types.Path) -> None:
|
| 192 |
+
"""
|
| 193 |
+
Export a flow to path.
|
| 194 |
+
"""
|
| 195 |
+
if format not in formats:
|
| 196 |
+
raise exceptions.CommandError("No such export format: %s" % format)
|
| 197 |
+
v = formats[format](flow)
|
| 198 |
+
try:
|
| 199 |
+
with open(path, "wb") as fp:
|
| 200 |
+
if isinstance(v, bytes):
|
| 201 |
+
fp.write(v)
|
| 202 |
+
else:
|
| 203 |
+
fp.write(v.encode("utf-8", "surrogateescape"))
|
| 204 |
+
except OSError as e:
|
| 205 |
+
logging.error(str(e))
|
| 206 |
+
|
| 207 |
+
@command.command("export.clip")
|
| 208 |
+
def clip(self, format: str, f: flow.Flow) -> None:
|
| 209 |
+
"""
|
| 210 |
+
Export a flow to the system clipboard.
|
| 211 |
+
"""
|
| 212 |
+
content = self.export_str(format, f)
|
| 213 |
+
try:
|
| 214 |
+
pyperclip.copy(content)
|
| 215 |
+
except pyperclip.PyperclipException as e:
|
| 216 |
+
logging.error(str(e))
|
| 217 |
+
|
| 218 |
+
@command.command("export")
|
| 219 |
+
def export_str(self, format: str, f: flow.Flow) -> str:
|
| 220 |
+
"""
|
| 221 |
+
Export a flow and return the result.
|
| 222 |
+
"""
|
| 223 |
+
if format not in formats:
|
| 224 |
+
raise exceptions.CommandError("No such export format: %s" % format)
|
| 225 |
+
|
| 226 |
+
content = formats[format](f)
|
| 227 |
+
# The individual formatters may return surrogate-escaped UTF-8, but that may blow up in later steps.
|
| 228 |
+
# For example, pyperclip on macOS does not like surrogates.
|
| 229 |
+
# To fix this, We first surrogate-encode and then backslash-decode.
|
| 230 |
+
content = strutils.always_bytes(content, "utf8", "surrogateescape")
|
| 231 |
+
content = strutils.always_str(content, "utf8", "backslashreplace")
|
| 232 |
+
return content
|
python/user_packages/Python313/site-packages/mitmproxy/addons/intercept.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
from mitmproxy import ctx
|
| 4 |
+
from mitmproxy import exceptions
|
| 5 |
+
from mitmproxy import flow
|
| 6 |
+
from mitmproxy import flowfilter
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Intercept:
|
| 10 |
+
filt: flowfilter.TFilter | None = None
|
| 11 |
+
|
| 12 |
+
def load(self, loader):
|
| 13 |
+
loader.add_option("intercept_active", bool, False, "Intercept toggle")
|
| 14 |
+
loader.add_option(
|
| 15 |
+
"intercept", Optional[str], None, "Intercept filter expression."
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
def configure(self, updated):
|
| 19 |
+
if "intercept" in updated:
|
| 20 |
+
if ctx.options.intercept:
|
| 21 |
+
try:
|
| 22 |
+
self.filt = flowfilter.parse(ctx.options.intercept)
|
| 23 |
+
except ValueError as e:
|
| 24 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 25 |
+
ctx.options.intercept_active = True
|
| 26 |
+
else:
|
| 27 |
+
self.filt = None
|
| 28 |
+
ctx.options.intercept_active = False
|
| 29 |
+
|
| 30 |
+
def should_intercept(self, f: flow.Flow) -> bool:
|
| 31 |
+
return bool(
|
| 32 |
+
ctx.options.intercept_active
|
| 33 |
+
and self.filt
|
| 34 |
+
and self.filt(f)
|
| 35 |
+
and not f.is_replay
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
def process_flow(self, f: flow.Flow) -> None:
|
| 39 |
+
if self.should_intercept(f):
|
| 40 |
+
f.intercept()
|
| 41 |
+
|
| 42 |
+
# Handlers
|
| 43 |
+
|
| 44 |
+
def request(self, f):
|
| 45 |
+
self.process_flow(f)
|
| 46 |
+
|
| 47 |
+
def response(self, f):
|
| 48 |
+
self.process_flow(f)
|
| 49 |
+
|
| 50 |
+
def tcp_message(self, f):
|
| 51 |
+
self.process_flow(f)
|
| 52 |
+
|
| 53 |
+
def udp_message(self, f):
|
| 54 |
+
self.process_flow(f)
|
| 55 |
+
|
| 56 |
+
def dns_request(self, f):
|
| 57 |
+
self.process_flow(f)
|
| 58 |
+
|
| 59 |
+
def dns_response(self, f):
|
| 60 |
+
self.process_flow(f)
|
| 61 |
+
|
| 62 |
+
def websocket_message(self, f):
|
| 63 |
+
self.process_flow(f)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/keepserving.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
|
| 5 |
+
from mitmproxy import ctx
|
| 6 |
+
from mitmproxy.utils import asyncio_utils
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class KeepServing:
|
| 10 |
+
def load(self, loader):
|
| 11 |
+
loader.add_option(
|
| 12 |
+
"keepserving",
|
| 13 |
+
bool,
|
| 14 |
+
False,
|
| 15 |
+
"""
|
| 16 |
+
Continue serving after client playback, server playback or file
|
| 17 |
+
read. This option is ignored by interactive tools, which always keep
|
| 18 |
+
serving.
|
| 19 |
+
""",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def keepgoing(self) -> bool:
|
| 23 |
+
# Checking for proxyserver.active_connections is important for server replay,
|
| 24 |
+
# the addon may report that replay is finished but not the entire response has been sent yet.
|
| 25 |
+
# (https://github.com/mitmproxy/mitmproxy/issues/7569)
|
| 26 |
+
checks = [
|
| 27 |
+
"readfile.reading",
|
| 28 |
+
"replay.client.count",
|
| 29 |
+
"replay.server.count",
|
| 30 |
+
"proxyserver.active_connections",
|
| 31 |
+
]
|
| 32 |
+
return any([ctx.master.commands.call(c) for c in checks])
|
| 33 |
+
|
| 34 |
+
def shutdown(self): # pragma: no cover
|
| 35 |
+
ctx.master.shutdown()
|
| 36 |
+
|
| 37 |
+
async def watch(self):
|
| 38 |
+
while True:
|
| 39 |
+
await asyncio.sleep(0.1)
|
| 40 |
+
if not self.keepgoing():
|
| 41 |
+
self.shutdown()
|
| 42 |
+
|
| 43 |
+
def running(self):
|
| 44 |
+
opts = [
|
| 45 |
+
ctx.options.client_replay,
|
| 46 |
+
ctx.options.server_replay,
|
| 47 |
+
ctx.options.rfile,
|
| 48 |
+
]
|
| 49 |
+
if any(opts) and not ctx.options.keepserving:
|
| 50 |
+
asyncio_utils.create_task(
|
| 51 |
+
self.watch(),
|
| 52 |
+
name="keepserving",
|
| 53 |
+
keep_ref=True,
|
| 54 |
+
)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/maplocal.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import mimetypes
|
| 3 |
+
import re
|
| 4 |
+
import urllib.parse
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import NamedTuple
|
| 8 |
+
|
| 9 |
+
from werkzeug.security import safe_join
|
| 10 |
+
|
| 11 |
+
from mitmproxy import ctx
|
| 12 |
+
from mitmproxy import exceptions
|
| 13 |
+
from mitmproxy import flowfilter
|
| 14 |
+
from mitmproxy import http
|
| 15 |
+
from mitmproxy import version
|
| 16 |
+
from mitmproxy.utils.spec import parse_spec
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MapLocalSpec(NamedTuple):
|
| 20 |
+
matches: flowfilter.TFilter
|
| 21 |
+
regex: str
|
| 22 |
+
local_path: Path
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def parse_map_local_spec(option: str) -> MapLocalSpec:
|
| 26 |
+
filter, regex, replacement = parse_spec(option)
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
re.compile(regex)
|
| 30 |
+
except re.error as e:
|
| 31 |
+
raise ValueError(f"Invalid regular expression {regex!r} ({e})")
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
path = Path(replacement).expanduser().resolve(strict=True)
|
| 35 |
+
except FileNotFoundError as e:
|
| 36 |
+
raise ValueError(f"Invalid file path: {replacement} ({e})")
|
| 37 |
+
|
| 38 |
+
return MapLocalSpec(filter, regex, path)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _safe_path_join(root: Path, untrusted: str) -> Path:
|
| 42 |
+
"""Join a Path element with an untrusted str.
|
| 43 |
+
|
| 44 |
+
This is a convenience wrapper for werkzeug's safe_join,
|
| 45 |
+
raising a ValueError if the path is malformed."""
|
| 46 |
+
untrusted_parts = Path(untrusted).parts
|
| 47 |
+
joined = safe_join(root.as_posix(), *untrusted_parts)
|
| 48 |
+
if joined is None:
|
| 49 |
+
raise ValueError("Untrusted paths.")
|
| 50 |
+
return Path(joined)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def file_candidates(url: str, spec: MapLocalSpec) -> list[Path]:
|
| 54 |
+
"""
|
| 55 |
+
Get all potential file candidates given a URL and a mapping spec ordered by preference.
|
| 56 |
+
This function already assumes that the spec regex matches the URL.
|
| 57 |
+
"""
|
| 58 |
+
m = re.search(spec.regex, url)
|
| 59 |
+
assert m
|
| 60 |
+
if m.groups():
|
| 61 |
+
suffix = m.group(1)
|
| 62 |
+
else:
|
| 63 |
+
suffix = re.split(spec.regex, url, maxsplit=1)[1]
|
| 64 |
+
suffix = suffix.split("?")[0] # remove query string
|
| 65 |
+
suffix = suffix.strip("/")
|
| 66 |
+
|
| 67 |
+
if suffix:
|
| 68 |
+
decoded_suffix = urllib.parse.unquote(suffix)
|
| 69 |
+
suffix_candidates = [decoded_suffix, f"{decoded_suffix}/index.html"]
|
| 70 |
+
|
| 71 |
+
escaped_suffix = re.sub(r"[^0-9a-zA-Z\-_.=(),/]", "_", decoded_suffix)
|
| 72 |
+
if decoded_suffix != escaped_suffix:
|
| 73 |
+
suffix_candidates.extend([escaped_suffix, f"{escaped_suffix}/index.html"])
|
| 74 |
+
try:
|
| 75 |
+
return [_safe_path_join(spec.local_path, x) for x in suffix_candidates]
|
| 76 |
+
except ValueError:
|
| 77 |
+
return []
|
| 78 |
+
else:
|
| 79 |
+
return [spec.local_path / "index.html"]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class MapLocal:
|
| 83 |
+
def __init__(self) -> None:
|
| 84 |
+
self.replacements: list[MapLocalSpec] = []
|
| 85 |
+
|
| 86 |
+
def load(self, loader):
|
| 87 |
+
loader.add_option(
|
| 88 |
+
"map_local",
|
| 89 |
+
Sequence[str],
|
| 90 |
+
[],
|
| 91 |
+
"""
|
| 92 |
+
Map remote resources to a local file using a pattern of the form
|
| 93 |
+
"[/flow-filter]/url-regex/file-or-directory-path", where the
|
| 94 |
+
separator can be any character.
|
| 95 |
+
""",
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def configure(self, updated):
|
| 99 |
+
if "map_local" in updated:
|
| 100 |
+
self.replacements = []
|
| 101 |
+
for option in ctx.options.map_local:
|
| 102 |
+
try:
|
| 103 |
+
spec = parse_map_local_spec(option)
|
| 104 |
+
except ValueError as e:
|
| 105 |
+
raise exceptions.OptionsError(
|
| 106 |
+
f"Cannot parse map_local option {option}: {e}"
|
| 107 |
+
) from e
|
| 108 |
+
|
| 109 |
+
self.replacements.append(spec)
|
| 110 |
+
|
| 111 |
+
def request(self, flow: http.HTTPFlow) -> None:
|
| 112 |
+
if flow.response or flow.error or not flow.live:
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
url = flow.request.pretty_url
|
| 116 |
+
|
| 117 |
+
all_candidates = []
|
| 118 |
+
for spec in self.replacements:
|
| 119 |
+
if spec.matches(flow) and re.search(spec.regex, url):
|
| 120 |
+
if spec.local_path.is_file():
|
| 121 |
+
candidates = [spec.local_path]
|
| 122 |
+
else:
|
| 123 |
+
candidates = file_candidates(url, spec)
|
| 124 |
+
all_candidates.extend(candidates)
|
| 125 |
+
|
| 126 |
+
local_file = None
|
| 127 |
+
for candidate in candidates:
|
| 128 |
+
if candidate.is_file():
|
| 129 |
+
local_file = candidate
|
| 130 |
+
break
|
| 131 |
+
|
| 132 |
+
if local_file:
|
| 133 |
+
headers = {"Server": version.MITMPROXY}
|
| 134 |
+
mimetype = mimetypes.guess_type(str(local_file))[0]
|
| 135 |
+
if mimetype:
|
| 136 |
+
headers["Content-Type"] = mimetype
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
contents = local_file.read_bytes()
|
| 140 |
+
except OSError as e:
|
| 141 |
+
logging.warning(f"Could not read file: {e}")
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
flow.response = http.Response.make(200, contents, headers)
|
| 145 |
+
# only set flow.response once, for the first matching rule
|
| 146 |
+
return
|
| 147 |
+
if all_candidates:
|
| 148 |
+
flow.response = http.Response.make(404)
|
| 149 |
+
logging.info(
|
| 150 |
+
f"None of the local file candidates exist: {', '.join(str(x) for x in all_candidates)}"
|
| 151 |
+
)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/mapremote.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from collections.abc import Sequence
|
| 3 |
+
from typing import NamedTuple
|
| 4 |
+
|
| 5 |
+
from mitmproxy import ctx
|
| 6 |
+
from mitmproxy import exceptions
|
| 7 |
+
from mitmproxy import flowfilter
|
| 8 |
+
from mitmproxy import http
|
| 9 |
+
from mitmproxy.utils.spec import parse_spec
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class MapRemoteSpec(NamedTuple):
|
| 13 |
+
matches: flowfilter.TFilter
|
| 14 |
+
subject: str
|
| 15 |
+
replacement: str
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_map_remote_spec(option: str) -> MapRemoteSpec:
|
| 19 |
+
spec = MapRemoteSpec(*parse_spec(option))
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
re.compile(spec.subject)
|
| 23 |
+
except re.error as e:
|
| 24 |
+
raise ValueError(f"Invalid regular expression {spec.subject!r} ({e})")
|
| 25 |
+
|
| 26 |
+
return spec
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class MapRemote:
|
| 30 |
+
def __init__(self) -> None:
|
| 31 |
+
self.replacements: list[MapRemoteSpec] = []
|
| 32 |
+
|
| 33 |
+
def load(self, loader):
|
| 34 |
+
loader.add_option(
|
| 35 |
+
"map_remote",
|
| 36 |
+
Sequence[str],
|
| 37 |
+
[],
|
| 38 |
+
"""
|
| 39 |
+
Map remote resources to another remote URL using a pattern of the form
|
| 40 |
+
"[/flow-filter]/url-regex/replacement", where the separator can
|
| 41 |
+
be any character.
|
| 42 |
+
""",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
def configure(self, updated):
|
| 46 |
+
if "map_remote" in updated:
|
| 47 |
+
self.replacements = []
|
| 48 |
+
for option in ctx.options.map_remote:
|
| 49 |
+
try:
|
| 50 |
+
spec = parse_map_remote_spec(option)
|
| 51 |
+
except ValueError as e:
|
| 52 |
+
raise exceptions.OptionsError(
|
| 53 |
+
f"Cannot parse map_remote option {option}: {e}"
|
| 54 |
+
) from e
|
| 55 |
+
|
| 56 |
+
self.replacements.append(spec)
|
| 57 |
+
|
| 58 |
+
def request(self, flow: http.HTTPFlow) -> None:
|
| 59 |
+
if flow.response or flow.error or not flow.live:
|
| 60 |
+
return
|
| 61 |
+
for spec in self.replacements:
|
| 62 |
+
if spec.matches(flow):
|
| 63 |
+
url = flow.request.pretty_url
|
| 64 |
+
new_url = re.sub(spec.subject, spec.replacement, url)
|
| 65 |
+
# this is a bit messy: setting .url also updates the host header,
|
| 66 |
+
# so we really only do that if the replacement affected the URL.
|
| 67 |
+
if url != new_url:
|
| 68 |
+
flow.request.url = new_url # type: ignore
|
python/user_packages/Python313/site-packages/mitmproxy/addons/modifybody.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
|
| 5 |
+
from mitmproxy import ctx
|
| 6 |
+
from mitmproxy import exceptions
|
| 7 |
+
from mitmproxy.addons.modifyheaders import ModifySpec
|
| 8 |
+
from mitmproxy.addons.modifyheaders import parse_modify_spec
|
| 9 |
+
from mitmproxy.log import ALERT
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ModifyBody:
|
| 15 |
+
def __init__(self) -> None:
|
| 16 |
+
self.replacements: list[ModifySpec] = []
|
| 17 |
+
|
| 18 |
+
def load(self, loader):
|
| 19 |
+
loader.add_option(
|
| 20 |
+
"modify_body",
|
| 21 |
+
Sequence[str],
|
| 22 |
+
[],
|
| 23 |
+
"""
|
| 24 |
+
Replacement pattern of the form "[/flow-filter]/regex/[@]replacement", where
|
| 25 |
+
the separator can be any character. The @ allows to provide a file path that
|
| 26 |
+
is used to read the replacement string.
|
| 27 |
+
""",
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def configure(self, updated):
|
| 31 |
+
if "modify_body" in updated:
|
| 32 |
+
self.replacements = []
|
| 33 |
+
for option in ctx.options.modify_body:
|
| 34 |
+
try:
|
| 35 |
+
spec = parse_modify_spec(option, True)
|
| 36 |
+
except ValueError as e:
|
| 37 |
+
raise exceptions.OptionsError(
|
| 38 |
+
f"Cannot parse modify_body option {option}: {e}"
|
| 39 |
+
) from e
|
| 40 |
+
|
| 41 |
+
self.replacements.append(spec)
|
| 42 |
+
|
| 43 |
+
stream_and_modify_conflict = (
|
| 44 |
+
ctx.options.modify_body
|
| 45 |
+
and ctx.options.stream_large_bodies
|
| 46 |
+
and ("modify_body" in updated or "stream_large_bodies" in updated)
|
| 47 |
+
)
|
| 48 |
+
if stream_and_modify_conflict:
|
| 49 |
+
logger.log(
|
| 50 |
+
ALERT,
|
| 51 |
+
"Both modify_body and stream_large_bodies are active. "
|
| 52 |
+
"Streamed bodies will not be modified.",
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def request(self, flow):
|
| 56 |
+
if flow.response or flow.error or not flow.live:
|
| 57 |
+
return
|
| 58 |
+
self.run(flow)
|
| 59 |
+
|
| 60 |
+
def response(self, flow):
|
| 61 |
+
if flow.error or not flow.live:
|
| 62 |
+
return
|
| 63 |
+
self.run(flow)
|
| 64 |
+
|
| 65 |
+
def run(self, flow):
|
| 66 |
+
for spec in self.replacements:
|
| 67 |
+
if spec.matches(flow):
|
| 68 |
+
try:
|
| 69 |
+
replacement = spec.read_replacement()
|
| 70 |
+
except OSError as e:
|
| 71 |
+
logging.warning(f"Could not read replacement file: {e}")
|
| 72 |
+
continue
|
| 73 |
+
if flow.response:
|
| 74 |
+
flow.response.content = re.sub(
|
| 75 |
+
spec.subject,
|
| 76 |
+
lambda _: replacement,
|
| 77 |
+
flow.response.content,
|
| 78 |
+
flags=re.DOTALL,
|
| 79 |
+
)
|
| 80 |
+
else:
|
| 81 |
+
flow.request.content = re.sub(
|
| 82 |
+
spec.subject,
|
| 83 |
+
lambda _: replacement,
|
| 84 |
+
flow.request.content,
|
| 85 |
+
flags=re.DOTALL,
|
| 86 |
+
)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/modifyheaders.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import NamedTuple
|
| 6 |
+
|
| 7 |
+
from mitmproxy import ctx
|
| 8 |
+
from mitmproxy import exceptions
|
| 9 |
+
from mitmproxy import flowfilter
|
| 10 |
+
from mitmproxy import http
|
| 11 |
+
from mitmproxy.http import Headers
|
| 12 |
+
from mitmproxy.utils import strutils
|
| 13 |
+
from mitmproxy.utils.spec import parse_spec
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ModifySpec(NamedTuple):
|
| 17 |
+
matches: flowfilter.TFilter
|
| 18 |
+
subject: bytes
|
| 19 |
+
replacement_str: str
|
| 20 |
+
|
| 21 |
+
def read_replacement(self) -> bytes:
|
| 22 |
+
"""
|
| 23 |
+
Process the replacement str. This usually just involves converting it to bytes.
|
| 24 |
+
However, if it starts with `@`, we interpret the rest as a file path to read from.
|
| 25 |
+
|
| 26 |
+
Raises:
|
| 27 |
+
- IOError if the file cannot be read.
|
| 28 |
+
"""
|
| 29 |
+
if self.replacement_str.startswith("@"):
|
| 30 |
+
return Path(self.replacement_str[1:]).expanduser().read_bytes()
|
| 31 |
+
else:
|
| 32 |
+
# We could cache this at some point, but unlikely to be a problem.
|
| 33 |
+
return strutils.escaped_str_to_bytes(self.replacement_str)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def parse_modify_spec(option: str, subject_is_regex: bool) -> ModifySpec:
|
| 37 |
+
flow_filter, subject_str, replacement = parse_spec(option)
|
| 38 |
+
|
| 39 |
+
subject = strutils.escaped_str_to_bytes(subject_str)
|
| 40 |
+
if subject_is_regex:
|
| 41 |
+
try:
|
| 42 |
+
re.compile(subject)
|
| 43 |
+
except re.error as e:
|
| 44 |
+
raise ValueError(f"Invalid regular expression {subject!r} ({e})")
|
| 45 |
+
|
| 46 |
+
spec = ModifySpec(flow_filter, subject, replacement)
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
spec.read_replacement()
|
| 50 |
+
except OSError as e:
|
| 51 |
+
raise ValueError(f"Invalid file path: {replacement[1:]} ({e})")
|
| 52 |
+
|
| 53 |
+
return spec
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ModifyHeaders:
|
| 57 |
+
def __init__(self) -> None:
|
| 58 |
+
self.replacements: list[ModifySpec] = []
|
| 59 |
+
|
| 60 |
+
def load(self, loader):
|
| 61 |
+
loader.add_option(
|
| 62 |
+
"modify_headers",
|
| 63 |
+
Sequence[str],
|
| 64 |
+
[],
|
| 65 |
+
"""
|
| 66 |
+
Header modify pattern of the form "[/flow-filter]/header-name/[@]header-value", where the
|
| 67 |
+
separator can be any character. The @ allows to provide a file path that is used to read
|
| 68 |
+
the header value string. An empty header-value removes existing header-name headers.
|
| 69 |
+
""",
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def configure(self, updated):
|
| 73 |
+
if "modify_headers" in updated:
|
| 74 |
+
self.replacements = []
|
| 75 |
+
for option in ctx.options.modify_headers:
|
| 76 |
+
try:
|
| 77 |
+
spec = parse_modify_spec(option, False)
|
| 78 |
+
except ValueError as e:
|
| 79 |
+
raise exceptions.OptionsError(
|
| 80 |
+
f"Cannot parse modify_headers option {option}: {e}"
|
| 81 |
+
) from e
|
| 82 |
+
self.replacements.append(spec)
|
| 83 |
+
|
| 84 |
+
def requestheaders(self, flow):
|
| 85 |
+
if flow.response or flow.error or not flow.live:
|
| 86 |
+
return
|
| 87 |
+
self.run(flow, flow.request.headers)
|
| 88 |
+
|
| 89 |
+
def responseheaders(self, flow):
|
| 90 |
+
if flow.error or not flow.live:
|
| 91 |
+
return
|
| 92 |
+
self.run(flow, flow.response.headers)
|
| 93 |
+
|
| 94 |
+
def run(self, flow: http.HTTPFlow, hdrs: Headers) -> None:
|
| 95 |
+
matches = []
|
| 96 |
+
|
| 97 |
+
# first check all the filters against the original, unmodified flow
|
| 98 |
+
for spec in self.replacements:
|
| 99 |
+
matches.append(spec.matches(flow))
|
| 100 |
+
|
| 101 |
+
# unset all specified headers
|
| 102 |
+
for i, spec in enumerate(self.replacements):
|
| 103 |
+
if matches[i]:
|
| 104 |
+
hdrs.pop(spec.subject, None)
|
| 105 |
+
|
| 106 |
+
# set all specified headers if the replacement string is not empty
|
| 107 |
+
|
| 108 |
+
for i, spec in enumerate(self.replacements):
|
| 109 |
+
if matches[i]:
|
| 110 |
+
try:
|
| 111 |
+
replacement = spec.read_replacement()
|
| 112 |
+
except OSError as e:
|
| 113 |
+
logging.warning(f"Could not read replacement file: {e}")
|
| 114 |
+
continue
|
| 115 |
+
else:
|
| 116 |
+
if replacement:
|
| 117 |
+
hdrs.add(spec.subject, replacement)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/next_layer.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This addon determines the next protocol layer in our proxy stack.
|
| 3 |
+
Whenever a protocol layer in the proxy wants to pass a connection to a child layer and isn't sure which protocol comes
|
| 4 |
+
next, it calls the `next_layer` hook, which ends up here.
|
| 5 |
+
For example, if mitmproxy runs as a regular proxy, we first need to determine if
|
| 6 |
+
new clients start with a TLS handshake right away (Secure Web Proxy) or send a plaintext HTTP CONNECT request.
|
| 7 |
+
This addon here peeks at the incoming bytes and then makes a decision based on proxy mode, mitmproxy options, etc.
|
| 8 |
+
|
| 9 |
+
For a typical HTTPS request, this addon is called a couple of times: First to determine that we start with an HTTP layer
|
| 10 |
+
which processes the `CONNECT` request, a second time to determine that the client then starts negotiating TLS, and a
|
| 11 |
+
third time when we check if the protocol within that TLS stream is actually HTTP or something else.
|
| 12 |
+
|
| 13 |
+
Sometimes it's useful to hardcode specific logic in next_layer when one wants to do fancy things.
|
| 14 |
+
In that case it's not necessary to modify mitmproxy's source, adding a custom addon with a next_layer event hook
|
| 15 |
+
that sets nextlayer.layer works just as well.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import logging
|
| 21 |
+
import re
|
| 22 |
+
import sys
|
| 23 |
+
from collections.abc import Iterable
|
| 24 |
+
from collections.abc import Sequence
|
| 25 |
+
from typing import Any
|
| 26 |
+
from typing import cast
|
| 27 |
+
|
| 28 |
+
from mitmproxy import ctx
|
| 29 |
+
from mitmproxy.connection import Address
|
| 30 |
+
from mitmproxy.net.tls import starts_like_dtls_record
|
| 31 |
+
from mitmproxy.net.tls import starts_like_tls_record
|
| 32 |
+
from mitmproxy.proxy import layer
|
| 33 |
+
from mitmproxy.proxy import layers
|
| 34 |
+
from mitmproxy.proxy import mode_specs
|
| 35 |
+
from mitmproxy.proxy import tunnel
|
| 36 |
+
from mitmproxy.proxy.context import Context
|
| 37 |
+
from mitmproxy.proxy.layer import Layer
|
| 38 |
+
from mitmproxy.proxy.layers import ClientQuicLayer
|
| 39 |
+
from mitmproxy.proxy.layers import ClientTLSLayer
|
| 40 |
+
from mitmproxy.proxy.layers import DNSLayer
|
| 41 |
+
from mitmproxy.proxy.layers import HttpLayer
|
| 42 |
+
from mitmproxy.proxy.layers import modes
|
| 43 |
+
from mitmproxy.proxy.layers import RawQuicLayer
|
| 44 |
+
from mitmproxy.proxy.layers import ServerQuicLayer
|
| 45 |
+
from mitmproxy.proxy.layers import ServerTLSLayer
|
| 46 |
+
from mitmproxy.proxy.layers import TCPLayer
|
| 47 |
+
from mitmproxy.proxy.layers import UDPLayer
|
| 48 |
+
from mitmproxy.proxy.layers.http import HTTPMode
|
| 49 |
+
from mitmproxy.proxy.layers.quic import quic_parse_client_hello_from_datagrams
|
| 50 |
+
from mitmproxy.proxy.layers.tls import dtls_parse_client_hello
|
| 51 |
+
from mitmproxy.proxy.layers.tls import HTTP_ALPNS
|
| 52 |
+
from mitmproxy.proxy.layers.tls import parse_client_hello
|
| 53 |
+
from mitmproxy.tls import ClientHello
|
| 54 |
+
|
| 55 |
+
if sys.version_info < (3, 11):
|
| 56 |
+
from typing_extensions import assert_never
|
| 57 |
+
else:
|
| 58 |
+
from typing import assert_never
|
| 59 |
+
|
| 60 |
+
logger = logging.getLogger(__name__)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def stack_match(
|
| 64 |
+
context: Context, layers: Sequence[type[Layer] | tuple[type[Layer], ...]]
|
| 65 |
+
) -> bool:
|
| 66 |
+
if len(context.layers) != len(layers):
|
| 67 |
+
return False
|
| 68 |
+
return all(
|
| 69 |
+
expected is Any or isinstance(actual, expected)
|
| 70 |
+
for actual, expected in zip(context.layers, layers)
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class NeedsMoreData(Exception):
|
| 75 |
+
"""Signal that the decision on which layer to put next needs to be deferred within the NextLayer addon."""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class NextLayer:
|
| 79 |
+
ignore_hosts: Sequence[re.Pattern] = ()
|
| 80 |
+
allow_hosts: Sequence[re.Pattern] = ()
|
| 81 |
+
tcp_hosts: Sequence[re.Pattern] = ()
|
| 82 |
+
udp_hosts: Sequence[re.Pattern] = ()
|
| 83 |
+
|
| 84 |
+
def configure(self, updated):
|
| 85 |
+
if "tcp_hosts" in updated:
|
| 86 |
+
self.tcp_hosts = [
|
| 87 |
+
re.compile(x, re.IGNORECASE) for x in ctx.options.tcp_hosts
|
| 88 |
+
]
|
| 89 |
+
if "udp_hosts" in updated:
|
| 90 |
+
self.udp_hosts = [
|
| 91 |
+
re.compile(x, re.IGNORECASE) for x in ctx.options.udp_hosts
|
| 92 |
+
]
|
| 93 |
+
if "allow_hosts" in updated or "ignore_hosts" in updated:
|
| 94 |
+
self.ignore_hosts = [
|
| 95 |
+
re.compile(x, re.IGNORECASE) for x in ctx.options.ignore_hosts
|
| 96 |
+
]
|
| 97 |
+
self.allow_hosts = [
|
| 98 |
+
re.compile(x, re.IGNORECASE) for x in ctx.options.allow_hosts
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
def next_layer(self, nextlayer: layer.NextLayer):
|
| 102 |
+
if nextlayer.layer:
|
| 103 |
+
return # do not override something another addon has set.
|
| 104 |
+
try:
|
| 105 |
+
nextlayer.layer = self._next_layer(
|
| 106 |
+
nextlayer.context,
|
| 107 |
+
nextlayer.data_client(),
|
| 108 |
+
nextlayer.data_server(),
|
| 109 |
+
)
|
| 110 |
+
except NeedsMoreData:
|
| 111 |
+
logger.debug(
|
| 112 |
+
f"Deferring layer decision, not enough data: {nextlayer.data_client().hex()!r}"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def _next_layer(
|
| 116 |
+
self, context: Context, data_client: bytes, data_server: bytes
|
| 117 |
+
) -> Layer | None:
|
| 118 |
+
assert context.layers
|
| 119 |
+
|
| 120 |
+
def s(*layers):
|
| 121 |
+
return stack_match(context, layers)
|
| 122 |
+
|
| 123 |
+
tcp_based = context.client.transport_protocol == "tcp"
|
| 124 |
+
udp_based = context.client.transport_protocol == "udp"
|
| 125 |
+
|
| 126 |
+
# 1) check for --ignore/--allow
|
| 127 |
+
if self._ignore_connection(context, data_client, data_server):
|
| 128 |
+
return (
|
| 129 |
+
layers.TCPLayer(context, ignore=not ctx.options.show_ignored_hosts)
|
| 130 |
+
if tcp_based
|
| 131 |
+
else layers.UDPLayer(context, ignore=not ctx.options.show_ignored_hosts)
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# 2) Handle proxy modes with well-defined next protocol
|
| 135 |
+
# 2a) Reverse proxy: derive from spec
|
| 136 |
+
if s(modes.ReverseProxy):
|
| 137 |
+
return self._setup_reverse_proxy(context, data_client)
|
| 138 |
+
# 2b) Explicit HTTP proxies
|
| 139 |
+
if s((modes.HttpProxy, modes.HttpUpstreamProxy)):
|
| 140 |
+
return self._setup_explicit_http_proxy(context, data_client)
|
| 141 |
+
|
| 142 |
+
# 3) Handle security protocols
|
| 143 |
+
# 3a) TLS/DTLS
|
| 144 |
+
is_tls_or_dtls = (
|
| 145 |
+
tcp_based
|
| 146 |
+
and starts_like_tls_record(data_client)
|
| 147 |
+
or udp_based
|
| 148 |
+
and starts_like_dtls_record(data_client)
|
| 149 |
+
)
|
| 150 |
+
if is_tls_or_dtls:
|
| 151 |
+
server_tls = ServerTLSLayer(context)
|
| 152 |
+
server_tls.child_layer = ClientTLSLayer(context)
|
| 153 |
+
return server_tls
|
| 154 |
+
# 3b) QUIC
|
| 155 |
+
if udp_based and _starts_like_quic(data_client, context.server.address):
|
| 156 |
+
server_quic = ServerQuicLayer(context)
|
| 157 |
+
server_quic.child_layer = ClientQuicLayer(context)
|
| 158 |
+
return server_quic
|
| 159 |
+
|
| 160 |
+
# 4) Check for --tcp/--udp
|
| 161 |
+
if tcp_based and self._is_destination_in_hosts(context, self.tcp_hosts):
|
| 162 |
+
return layers.TCPLayer(context)
|
| 163 |
+
if udp_based and self._is_destination_in_hosts(context, self.udp_hosts):
|
| 164 |
+
return layers.UDPLayer(context)
|
| 165 |
+
|
| 166 |
+
# 5) Handle application protocol
|
| 167 |
+
# 5a) Do we have a known ALPN negotiation?
|
| 168 |
+
if context.client.alpn:
|
| 169 |
+
if context.client.alpn in HTTP_ALPNS:
|
| 170 |
+
return layers.HttpLayer(context, HTTPMode.transparent)
|
| 171 |
+
elif context.client.tls_version == "QUICv1":
|
| 172 |
+
# TODO: Once we support more QUIC-based protocols, relax force_raw here.
|
| 173 |
+
return layers.RawQuicLayer(context, force_raw=True)
|
| 174 |
+
# 5b) Is it DNS?
|
| 175 |
+
if context.server.address and context.server.address[1] in (53, 5353):
|
| 176 |
+
return layers.DNSLayer(context)
|
| 177 |
+
# 5c) We have no other specialized layers for UDP, so we fall back to raw forwarding.
|
| 178 |
+
if udp_based:
|
| 179 |
+
return layers.UDPLayer(context)
|
| 180 |
+
# 5d) Check for raw tcp mode.
|
| 181 |
+
probably_no_http = (
|
| 182 |
+
# the first three bytes should be the HTTP verb, so A-Za-z is expected.
|
| 183 |
+
len(data_client) < 3
|
| 184 |
+
# HTTP would require whitespace...
|
| 185 |
+
or b" " not in data_client
|
| 186 |
+
# ...and that whitespace needs to be in the first line.
|
| 187 |
+
or (data_client.find(b" ") > data_client.find(b"\n"))
|
| 188 |
+
or not data_client[:3].isalpha()
|
| 189 |
+
# a server greeting would be uncharacteristic.
|
| 190 |
+
or data_server
|
| 191 |
+
or data_client.startswith(b"SSH")
|
| 192 |
+
)
|
| 193 |
+
if ctx.options.rawtcp and probably_no_http:
|
| 194 |
+
return layers.TCPLayer(context)
|
| 195 |
+
# 5c) Assume HTTP by default.
|
| 196 |
+
return layers.HttpLayer(context, HTTPMode.transparent)
|
| 197 |
+
|
| 198 |
+
def _ignore_connection(
|
| 199 |
+
self,
|
| 200 |
+
context: Context,
|
| 201 |
+
data_client: bytes,
|
| 202 |
+
data_server: bytes,
|
| 203 |
+
) -> bool | None:
|
| 204 |
+
"""
|
| 205 |
+
Returns:
|
| 206 |
+
True, if the connection should be ignored.
|
| 207 |
+
False, if it should not be ignored.
|
| 208 |
+
|
| 209 |
+
Raises:
|
| 210 |
+
NeedsMoreData, if we need to wait for more input data.
|
| 211 |
+
"""
|
| 212 |
+
if not ctx.options.ignore_hosts and not ctx.options.allow_hosts:
|
| 213 |
+
return False
|
| 214 |
+
# Special handling for wireguard mode: if the hostname is "10.0.0.53", do not ignore the connection
|
| 215 |
+
if isinstance(
|
| 216 |
+
context.client.proxy_mode, mode_specs.WireGuardMode
|
| 217 |
+
) and context.server.address == ("10.0.0.53", 53):
|
| 218 |
+
return False
|
| 219 |
+
hostnames: list[str] = []
|
| 220 |
+
if context.server.peername:
|
| 221 |
+
host, port, *_ = context.server.peername
|
| 222 |
+
hostnames.append(f"{host}:{port}")
|
| 223 |
+
if context.server.address:
|
| 224 |
+
host, port, *_ = context.server.address
|
| 225 |
+
hostnames.append(f"{host}:{port}")
|
| 226 |
+
|
| 227 |
+
# We also want to check for TLS SNI and HTTP host headers, but in order to ignore connections based on that
|
| 228 |
+
# they must have a destination address. If they don't, we don't know how to establish an upstream connection
|
| 229 |
+
# if we ignore.
|
| 230 |
+
if host_header := self._get_host_header(context, data_client, data_server):
|
| 231 |
+
if not re.search(r":\d+$", host_header):
|
| 232 |
+
host_header = f"{host_header}:{port}"
|
| 233 |
+
hostnames.append(host_header)
|
| 234 |
+
if (
|
| 235 |
+
client_hello := self._get_client_hello(context, data_client)
|
| 236 |
+
) and client_hello.sni:
|
| 237 |
+
hostnames.append(f"{client_hello.sni}:{port}")
|
| 238 |
+
if context.client.sni:
|
| 239 |
+
# Hostname may be allowed, TLS is already established, and we have another next layer decision.
|
| 240 |
+
hostnames.append(f"{context.client.sni}:{port}")
|
| 241 |
+
|
| 242 |
+
if not hostnames:
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
if ctx.options.allow_hosts:
|
| 246 |
+
not_allowed = not any(
|
| 247 |
+
re.search(rex, host, re.IGNORECASE)
|
| 248 |
+
for host in hostnames
|
| 249 |
+
for rex in ctx.options.allow_hosts
|
| 250 |
+
)
|
| 251 |
+
if not_allowed:
|
| 252 |
+
return True
|
| 253 |
+
|
| 254 |
+
if ctx.options.ignore_hosts:
|
| 255 |
+
ignored = any(
|
| 256 |
+
re.search(rex, host, re.IGNORECASE)
|
| 257 |
+
for host in hostnames
|
| 258 |
+
for rex in ctx.options.ignore_hosts
|
| 259 |
+
)
|
| 260 |
+
if ignored:
|
| 261 |
+
return True
|
| 262 |
+
|
| 263 |
+
return False
|
| 264 |
+
|
| 265 |
+
@staticmethod
|
| 266 |
+
def _get_host_header(
|
| 267 |
+
context: Context,
|
| 268 |
+
data_client: bytes,
|
| 269 |
+
data_server: bytes,
|
| 270 |
+
) -> str | None:
|
| 271 |
+
"""
|
| 272 |
+
Try to read a host header from data_client.
|
| 273 |
+
|
| 274 |
+
Returns:
|
| 275 |
+
The host header value, or None, if no host header was found.
|
| 276 |
+
|
| 277 |
+
Raises:
|
| 278 |
+
NeedsMoreData, if the HTTP request is incomplete.
|
| 279 |
+
"""
|
| 280 |
+
if context.client.transport_protocol != "tcp" or data_server:
|
| 281 |
+
return None
|
| 282 |
+
|
| 283 |
+
host_header_expected = re.match(
|
| 284 |
+
rb"[A-Z]{3,}.+HTTP/", data_client, re.IGNORECASE
|
| 285 |
+
)
|
| 286 |
+
if host_header_expected:
|
| 287 |
+
if m := re.search(
|
| 288 |
+
rb"\r\n(?:Host:\s+(.+?)\s*)?\r\n", data_client, re.IGNORECASE
|
| 289 |
+
):
|
| 290 |
+
if host := m.group(1):
|
| 291 |
+
return host.decode("utf-8", "surrogateescape")
|
| 292 |
+
else:
|
| 293 |
+
return None # \r\n\r\n - header end came first.
|
| 294 |
+
else:
|
| 295 |
+
raise NeedsMoreData
|
| 296 |
+
else:
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
@staticmethod
|
| 300 |
+
def _get_client_hello(context: Context, data_client: bytes) -> ClientHello | None:
|
| 301 |
+
"""
|
| 302 |
+
Try to read a TLS/DTLS/QUIC ClientHello from data_client.
|
| 303 |
+
|
| 304 |
+
Returns:
|
| 305 |
+
A complete ClientHello, or None, if no ClientHello was found.
|
| 306 |
+
|
| 307 |
+
Raises:
|
| 308 |
+
NeedsMoreData, if the ClientHello is incomplete.
|
| 309 |
+
"""
|
| 310 |
+
match context.client.transport_protocol:
|
| 311 |
+
case "tcp":
|
| 312 |
+
if starts_like_tls_record(data_client):
|
| 313 |
+
try:
|
| 314 |
+
ch = parse_client_hello(data_client)
|
| 315 |
+
except ValueError:
|
| 316 |
+
pass
|
| 317 |
+
else:
|
| 318 |
+
if ch is None:
|
| 319 |
+
raise NeedsMoreData
|
| 320 |
+
return ch
|
| 321 |
+
return None
|
| 322 |
+
case "udp":
|
| 323 |
+
try:
|
| 324 |
+
return quic_parse_client_hello_from_datagrams([data_client])
|
| 325 |
+
except ValueError:
|
| 326 |
+
pass
|
| 327 |
+
|
| 328 |
+
try:
|
| 329 |
+
ch = dtls_parse_client_hello(data_client)
|
| 330 |
+
except ValueError:
|
| 331 |
+
pass
|
| 332 |
+
else:
|
| 333 |
+
if ch is None:
|
| 334 |
+
raise NeedsMoreData
|
| 335 |
+
return ch
|
| 336 |
+
return None
|
| 337 |
+
case _: # pragma: no cover
|
| 338 |
+
assert_never(context.client.transport_protocol)
|
| 339 |
+
|
| 340 |
+
@staticmethod
|
| 341 |
+
def _setup_reverse_proxy(context: Context, data_client: bytes) -> Layer:
|
| 342 |
+
spec = cast(mode_specs.ReverseMode, context.client.proxy_mode)
|
| 343 |
+
stack = tunnel.LayerStack()
|
| 344 |
+
|
| 345 |
+
match spec.scheme:
|
| 346 |
+
case "http":
|
| 347 |
+
if starts_like_tls_record(data_client):
|
| 348 |
+
stack /= ClientTLSLayer(context)
|
| 349 |
+
stack /= HttpLayer(context, HTTPMode.transparent)
|
| 350 |
+
case "https":
|
| 351 |
+
if context.client.transport_protocol == "udp":
|
| 352 |
+
stack /= ServerQuicLayer(context)
|
| 353 |
+
stack /= ClientQuicLayer(context)
|
| 354 |
+
stack /= HttpLayer(context, HTTPMode.transparent)
|
| 355 |
+
else:
|
| 356 |
+
stack /= ServerTLSLayer(context)
|
| 357 |
+
if starts_like_tls_record(data_client):
|
| 358 |
+
stack /= ClientTLSLayer(context)
|
| 359 |
+
stack /= HttpLayer(context, HTTPMode.transparent)
|
| 360 |
+
|
| 361 |
+
case "tcp":
|
| 362 |
+
if starts_like_tls_record(data_client):
|
| 363 |
+
stack /= ClientTLSLayer(context)
|
| 364 |
+
stack /= TCPLayer(context)
|
| 365 |
+
case "tls":
|
| 366 |
+
stack /= ServerTLSLayer(context)
|
| 367 |
+
if starts_like_tls_record(data_client):
|
| 368 |
+
stack /= ClientTLSLayer(context)
|
| 369 |
+
stack /= TCPLayer(context)
|
| 370 |
+
|
| 371 |
+
case "udp":
|
| 372 |
+
if starts_like_dtls_record(data_client):
|
| 373 |
+
stack /= ClientTLSLayer(context)
|
| 374 |
+
stack /= UDPLayer(context)
|
| 375 |
+
case "dtls":
|
| 376 |
+
stack /= ServerTLSLayer(context)
|
| 377 |
+
if starts_like_dtls_record(data_client):
|
| 378 |
+
stack /= ClientTLSLayer(context)
|
| 379 |
+
stack /= UDPLayer(context)
|
| 380 |
+
|
| 381 |
+
case "dns":
|
| 382 |
+
# TODO: DNS-over-TLS / DNS-over-DTLS
|
| 383 |
+
# is_tls_or_dtls = (
|
| 384 |
+
# context.client.transport_protocol == "tcp" and starts_like_tls_record(data_client)
|
| 385 |
+
# or
|
| 386 |
+
# context.client.transport_protocol == "udp" and starts_like_dtls_record(data_client)
|
| 387 |
+
# )
|
| 388 |
+
# if is_tls_or_dtls:
|
| 389 |
+
# stack /= ClientTLSLayer(context)
|
| 390 |
+
stack /= DNSLayer(context)
|
| 391 |
+
|
| 392 |
+
case "http3":
|
| 393 |
+
stack /= ServerQuicLayer(context)
|
| 394 |
+
stack /= ClientQuicLayer(context)
|
| 395 |
+
stack /= HttpLayer(context, HTTPMode.transparent)
|
| 396 |
+
case "quic":
|
| 397 |
+
stack /= ServerQuicLayer(context)
|
| 398 |
+
stack /= ClientQuicLayer(context)
|
| 399 |
+
stack /= RawQuicLayer(context, force_raw=True)
|
| 400 |
+
|
| 401 |
+
case _: # pragma: no cover
|
| 402 |
+
assert_never(spec.scheme)
|
| 403 |
+
|
| 404 |
+
return stack[0]
|
| 405 |
+
|
| 406 |
+
@staticmethod
|
| 407 |
+
def _setup_explicit_http_proxy(context: Context, data_client: bytes) -> Layer:
|
| 408 |
+
stack = tunnel.LayerStack()
|
| 409 |
+
|
| 410 |
+
if context.client.transport_protocol == "udp":
|
| 411 |
+
stack /= layers.ClientQuicLayer(context)
|
| 412 |
+
elif starts_like_tls_record(data_client):
|
| 413 |
+
stack /= layers.ClientTLSLayer(context)
|
| 414 |
+
|
| 415 |
+
if isinstance(context.layers[0], modes.HttpUpstreamProxy):
|
| 416 |
+
stack /= layers.HttpLayer(context, HTTPMode.upstream)
|
| 417 |
+
else:
|
| 418 |
+
stack /= layers.HttpLayer(context, HTTPMode.regular)
|
| 419 |
+
|
| 420 |
+
return stack[0]
|
| 421 |
+
|
| 422 |
+
@staticmethod
|
| 423 |
+
def _is_destination_in_hosts(context: Context, hosts: Iterable[re.Pattern]) -> bool:
|
| 424 |
+
return any(
|
| 425 |
+
(context.server.address and rex.search(context.server.address[0]))
|
| 426 |
+
or (context.client.sni and rex.search(context.client.sni))
|
| 427 |
+
for rex in hosts
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
# https://www.iana.org/assignments/quic/quic.xhtml
|
| 432 |
+
KNOWN_QUIC_VERSIONS = {
|
| 433 |
+
0x00000001, # QUIC v1
|
| 434 |
+
0x51303433, # Google QUIC Q043
|
| 435 |
+
0x51303436, # Google QUIC Q046
|
| 436 |
+
0x51303530, # Google QUIC Q050
|
| 437 |
+
0x6B3343CF, # QUIC v2
|
| 438 |
+
0x709A50C4, # QUIC v2 draft codepoint
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
TYPICAL_QUIC_PORTS = {80, 443, 8443}
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _starts_like_quic(data_client: bytes, server_address: Address | None) -> bool:
|
| 445 |
+
"""
|
| 446 |
+
Make an educated guess on whether this could be QUIC.
|
| 447 |
+
This turns out to be quite hard in practice as 1-RTT packets are hardly distinguishable from noise.
|
| 448 |
+
|
| 449 |
+
Returns:
|
| 450 |
+
True, if the passed bytes could be the start of a QUIC packet.
|
| 451 |
+
False, otherwise.
|
| 452 |
+
"""
|
| 453 |
+
# Minimum size: 1 flag byte + 1+ packet number bytes + 16+ bytes encrypted payload
|
| 454 |
+
if len(data_client) < 18:
|
| 455 |
+
return False
|
| 456 |
+
if starts_like_dtls_record(data_client):
|
| 457 |
+
return False
|
| 458 |
+
# TODO: Add more checks here to detect true negatives.
|
| 459 |
+
|
| 460 |
+
# Long Header Packets
|
| 461 |
+
if data_client[0] & 0x80:
|
| 462 |
+
version = int.from_bytes(data_client[1:5], "big")
|
| 463 |
+
if version in KNOWN_QUIC_VERSIONS:
|
| 464 |
+
return True
|
| 465 |
+
# https://www.rfc-editor.org/rfc/rfc9000.html#name-versions
|
| 466 |
+
# Versions that follow the pattern 0x?a?a?a?a are reserved for use in forcing version negotiation
|
| 467 |
+
if version & 0x0F0F0F0F == 0x0A0A0A0A:
|
| 468 |
+
return True
|
| 469 |
+
else:
|
| 470 |
+
# ¯\_(ツ)_/¯
|
| 471 |
+
# We can't even rely on the QUIC bit, see https://datatracker.ietf.org/doc/rfc9287/.
|
| 472 |
+
pass
|
| 473 |
+
|
| 474 |
+
return bool(server_address and server_address[1] in TYPICAL_QUIC_PORTS)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/onboarding.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mitmproxy import ctx
|
| 2 |
+
from mitmproxy.addons import asgiapp
|
| 3 |
+
from mitmproxy.addons.onboardingapp import app
|
| 4 |
+
|
| 5 |
+
APP_HOST = "mitm.it"
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Onboarding(asgiapp.WSGIApp):
|
| 9 |
+
name = "onboarding"
|
| 10 |
+
|
| 11 |
+
def __init__(self):
|
| 12 |
+
super().__init__(app, APP_HOST, None)
|
| 13 |
+
|
| 14 |
+
def load(self, loader):
|
| 15 |
+
loader.add_option(
|
| 16 |
+
"onboarding", bool, True, "Toggle the mitmproxy onboarding app."
|
| 17 |
+
)
|
| 18 |
+
loader.add_option(
|
| 19 |
+
"onboarding_host",
|
| 20 |
+
str,
|
| 21 |
+
APP_HOST,
|
| 22 |
+
"""
|
| 23 |
+
Onboarding app domain. For transparent mode, use an IP when a DNS
|
| 24 |
+
entry for the app domain is not present.
|
| 25 |
+
""",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
def configure(self, updated):
|
| 29 |
+
self.host = ctx.options.onboarding_host
|
| 30 |
+
app.config["CONFDIR"] = ctx.options.confdir
|
| 31 |
+
|
| 32 |
+
async def request(self, f):
|
| 33 |
+
if ctx.options.onboarding:
|
| 34 |
+
await super().request(f)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/proxyauth.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import binascii
|
| 4 |
+
import pathlib
|
| 5 |
+
import weakref
|
| 6 |
+
from abc import ABC
|
| 7 |
+
from abc import abstractmethod
|
| 8 |
+
from collections.abc import MutableMapping
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
import ldap3
|
| 12 |
+
|
| 13 |
+
from mitmproxy import connection
|
| 14 |
+
from mitmproxy import ctx
|
| 15 |
+
from mitmproxy import exceptions
|
| 16 |
+
from mitmproxy import http
|
| 17 |
+
from mitmproxy.net.http import status_codes
|
| 18 |
+
from mitmproxy.proxy import mode_specs
|
| 19 |
+
from mitmproxy.proxy.layers import modes
|
| 20 |
+
from mitmproxy.utils import htpasswd
|
| 21 |
+
|
| 22 |
+
REALM = "mitmproxy"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ProxyAuth:
|
| 26 |
+
validator: Validator | None = None
|
| 27 |
+
|
| 28 |
+
def __init__(self) -> None:
|
| 29 |
+
self.authenticated: MutableMapping[connection.Client, tuple[str, str]] = (
|
| 30 |
+
weakref.WeakKeyDictionary()
|
| 31 |
+
)
|
| 32 |
+
"""Contains all connections that are permanently authenticated after an HTTP CONNECT"""
|
| 33 |
+
|
| 34 |
+
def load(self, loader):
|
| 35 |
+
loader.add_option(
|
| 36 |
+
"proxyauth",
|
| 37 |
+
Optional[str],
|
| 38 |
+
None,
|
| 39 |
+
"""
|
| 40 |
+
Require proxy authentication. Format:
|
| 41 |
+
"username:pass",
|
| 42 |
+
"any" to accept any user/pass combination,
|
| 43 |
+
"@path" to use an Apache htpasswd file,
|
| 44 |
+
or "ldap[s]:url_server_ldap[:port]:dn_auth:password:dn_subtree[?search_filter_key=...]" for LDAP authentication.
|
| 45 |
+
""",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def configure(self, updated):
|
| 49 |
+
if "proxyauth" in updated:
|
| 50 |
+
auth = ctx.options.proxyauth
|
| 51 |
+
if auth:
|
| 52 |
+
if auth == "any":
|
| 53 |
+
self.validator = AcceptAll()
|
| 54 |
+
elif auth.startswith("@"):
|
| 55 |
+
self.validator = Htpasswd(auth)
|
| 56 |
+
elif ctx.options.proxyauth.startswith("ldap"):
|
| 57 |
+
self.validator = Ldap(auth)
|
| 58 |
+
elif ":" in ctx.options.proxyauth:
|
| 59 |
+
self.validator = SingleUser(auth)
|
| 60 |
+
else:
|
| 61 |
+
raise exceptions.OptionsError("Invalid proxyauth specification.")
|
| 62 |
+
else:
|
| 63 |
+
self.validator = None
|
| 64 |
+
|
| 65 |
+
def socks5_auth(self, data: modes.Socks5AuthData) -> None:
|
| 66 |
+
if self.validator and self.validator(data.username, data.password):
|
| 67 |
+
data.valid = True
|
| 68 |
+
self.authenticated[data.client_conn] = data.username, data.password
|
| 69 |
+
|
| 70 |
+
def http_connect(self, f: http.HTTPFlow) -> None:
|
| 71 |
+
if self.validator and self.authenticate_http(f):
|
| 72 |
+
# Make a note that all further requests over this connection are ok.
|
| 73 |
+
self.authenticated[f.client_conn] = f.metadata["proxyauth"]
|
| 74 |
+
|
| 75 |
+
def requestheaders(self, f: http.HTTPFlow) -> None:
|
| 76 |
+
if self.validator:
|
| 77 |
+
# Is this connection authenticated by a previous HTTP CONNECT?
|
| 78 |
+
if f.client_conn in self.authenticated:
|
| 79 |
+
f.metadata["proxyauth"] = self.authenticated[f.client_conn]
|
| 80 |
+
elif f.is_replay:
|
| 81 |
+
pass
|
| 82 |
+
else:
|
| 83 |
+
self.authenticate_http(f)
|
| 84 |
+
|
| 85 |
+
def authenticate_http(self, f: http.HTTPFlow) -> bool:
|
| 86 |
+
"""
|
| 87 |
+
Authenticate an HTTP request, returns if authentication was successful.
|
| 88 |
+
|
| 89 |
+
If valid credentials are found, the matching authentication header is removed.
|
| 90 |
+
In no or invalid credentials are found, flow.response is set to an error page.
|
| 91 |
+
"""
|
| 92 |
+
assert self.validator
|
| 93 |
+
username = None
|
| 94 |
+
password = None
|
| 95 |
+
is_valid = False
|
| 96 |
+
|
| 97 |
+
is_proxy = is_http_proxy(f)
|
| 98 |
+
auth_header = http_auth_header(is_proxy)
|
| 99 |
+
try:
|
| 100 |
+
auth_value = f.request.headers.get(auth_header, "")
|
| 101 |
+
scheme, username, password = parse_http_basic_auth(auth_value)
|
| 102 |
+
is_valid = self.validator(username, password)
|
| 103 |
+
except Exception:
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
if is_valid:
|
| 107 |
+
f.metadata["proxyauth"] = (username, password)
|
| 108 |
+
del f.request.headers[auth_header]
|
| 109 |
+
return True
|
| 110 |
+
else:
|
| 111 |
+
f.response = make_auth_required_response(is_proxy)
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def make_auth_required_response(is_proxy: bool) -> http.Response:
|
| 116 |
+
if is_proxy:
|
| 117 |
+
status_code = status_codes.PROXY_AUTH_REQUIRED
|
| 118 |
+
headers = {"Proxy-Authenticate": f'Basic realm="{REALM}"'}
|
| 119 |
+
else:
|
| 120 |
+
status_code = status_codes.UNAUTHORIZED
|
| 121 |
+
headers = {"WWW-Authenticate": f'Basic realm="{REALM}"'}
|
| 122 |
+
|
| 123 |
+
reason = http.status_codes.RESPONSES[status_code]
|
| 124 |
+
return http.Response.make(
|
| 125 |
+
status_code,
|
| 126 |
+
(
|
| 127 |
+
f"<html>"
|
| 128 |
+
f"<head><title>{status_code} {reason}</title></head>"
|
| 129 |
+
f"<body><h1>{status_code} {reason}</h1></body>"
|
| 130 |
+
f"</html>"
|
| 131 |
+
),
|
| 132 |
+
headers,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def http_auth_header(is_proxy: bool) -> str:
|
| 137 |
+
if is_proxy:
|
| 138 |
+
return "Proxy-Authorization"
|
| 139 |
+
else:
|
| 140 |
+
return "Authorization"
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def is_http_proxy(f: http.HTTPFlow) -> bool:
|
| 144 |
+
"""
|
| 145 |
+
Returns:
|
| 146 |
+
- True, if authentication is done as if mitmproxy is a proxy
|
| 147 |
+
- False, if authentication is done as if mitmproxy is an HTTP server
|
| 148 |
+
"""
|
| 149 |
+
return isinstance(
|
| 150 |
+
f.client_conn.proxy_mode, (mode_specs.RegularMode, mode_specs.UpstreamMode)
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def mkauth(username: str, password: str, scheme: str = "basic") -> str:
|
| 155 |
+
"""
|
| 156 |
+
Craft a basic auth string
|
| 157 |
+
"""
|
| 158 |
+
v = binascii.b2a_base64((username + ":" + password).encode("utf8")).decode("ascii")
|
| 159 |
+
return scheme + " " + v
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def parse_http_basic_auth(s: str) -> tuple[str, str, str]:
|
| 163 |
+
"""
|
| 164 |
+
Parse a basic auth header.
|
| 165 |
+
Raises a ValueError if the input is invalid.
|
| 166 |
+
"""
|
| 167 |
+
scheme, authinfo = s.split()
|
| 168 |
+
if scheme.lower() != "basic":
|
| 169 |
+
raise ValueError("Unknown scheme")
|
| 170 |
+
try:
|
| 171 |
+
user, password = (
|
| 172 |
+
binascii.a2b_base64(authinfo.encode()).decode("utf8", "replace").split(":")
|
| 173 |
+
)
|
| 174 |
+
except binascii.Error as e:
|
| 175 |
+
raise ValueError(str(e))
|
| 176 |
+
return scheme, user, password
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Validator(ABC):
|
| 180 |
+
"""Base class for all username/password validators."""
|
| 181 |
+
|
| 182 |
+
@abstractmethod
|
| 183 |
+
def __call__(self, username: str, password: str) -> bool:
|
| 184 |
+
raise NotImplementedError
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class AcceptAll(Validator):
|
| 188 |
+
def __call__(self, username: str, password: str) -> bool:
|
| 189 |
+
return True
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class SingleUser(Validator):
|
| 193 |
+
def __init__(self, proxyauth: str):
|
| 194 |
+
try:
|
| 195 |
+
self.username, self.password = proxyauth.split(":")
|
| 196 |
+
except ValueError:
|
| 197 |
+
raise exceptions.OptionsError("Invalid single-user auth specification.")
|
| 198 |
+
|
| 199 |
+
def __call__(self, username: str, password: str) -> bool:
|
| 200 |
+
return self.username == username and self.password == password
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class Htpasswd(Validator):
|
| 204 |
+
def __init__(self, proxyauth: str):
|
| 205 |
+
path = pathlib.Path(proxyauth[1:]).expanduser()
|
| 206 |
+
try:
|
| 207 |
+
self.htpasswd = htpasswd.HtpasswdFile.from_file(path)
|
| 208 |
+
except (ValueError, OSError) as e:
|
| 209 |
+
raise exceptions.OptionsError(
|
| 210 |
+
f"Could not open htpasswd file: {path}"
|
| 211 |
+
) from e
|
| 212 |
+
|
| 213 |
+
def __call__(self, username: str, password: str) -> bool:
|
| 214 |
+
return self.htpasswd.check_password(username, password)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class Ldap(Validator):
|
| 218 |
+
conn: ldap3.Connection
|
| 219 |
+
server: ldap3.Server
|
| 220 |
+
dn_subtree: str
|
| 221 |
+
filter_key: str
|
| 222 |
+
|
| 223 |
+
def __init__(self, proxyauth: str):
|
| 224 |
+
(
|
| 225 |
+
use_ssl,
|
| 226 |
+
url,
|
| 227 |
+
port,
|
| 228 |
+
ldap_user,
|
| 229 |
+
ldap_pass,
|
| 230 |
+
self.dn_subtree,
|
| 231 |
+
self.filter_key,
|
| 232 |
+
) = self.parse_spec(proxyauth)
|
| 233 |
+
server = ldap3.Server(url, port=port, use_ssl=use_ssl)
|
| 234 |
+
conn = ldap3.Connection(server, ldap_user, ldap_pass, auto_bind=True)
|
| 235 |
+
self.conn = conn
|
| 236 |
+
self.server = server
|
| 237 |
+
|
| 238 |
+
@staticmethod
|
| 239 |
+
def parse_spec(spec: str) -> tuple[bool, str, int | None, str, str, str, str]:
|
| 240 |
+
try:
|
| 241 |
+
if spec.count(":") > 4:
|
| 242 |
+
(
|
| 243 |
+
security,
|
| 244 |
+
url,
|
| 245 |
+
port_str,
|
| 246 |
+
ldap_user,
|
| 247 |
+
ldap_pass,
|
| 248 |
+
dn_subtree,
|
| 249 |
+
) = spec.split(":")
|
| 250 |
+
port = int(port_str)
|
| 251 |
+
else:
|
| 252 |
+
security, url, ldap_user, ldap_pass, dn_subtree = spec.split(":")
|
| 253 |
+
port = None
|
| 254 |
+
|
| 255 |
+
if "?" in dn_subtree:
|
| 256 |
+
dn_subtree, search_str = dn_subtree.split("?")
|
| 257 |
+
key, value = search_str.split("=")
|
| 258 |
+
if key == "search_filter_key":
|
| 259 |
+
search_filter_key = value
|
| 260 |
+
else:
|
| 261 |
+
raise ValueError
|
| 262 |
+
else:
|
| 263 |
+
search_filter_key = "cn"
|
| 264 |
+
|
| 265 |
+
if security == "ldaps":
|
| 266 |
+
use_ssl = True
|
| 267 |
+
elif security == "ldap":
|
| 268 |
+
use_ssl = False
|
| 269 |
+
else:
|
| 270 |
+
raise ValueError
|
| 271 |
+
|
| 272 |
+
return (
|
| 273 |
+
use_ssl,
|
| 274 |
+
url,
|
| 275 |
+
port,
|
| 276 |
+
ldap_user,
|
| 277 |
+
ldap_pass,
|
| 278 |
+
dn_subtree,
|
| 279 |
+
search_filter_key,
|
| 280 |
+
)
|
| 281 |
+
except ValueError:
|
| 282 |
+
raise exceptions.OptionsError(f"Invalid LDAP specification: {spec}")
|
| 283 |
+
|
| 284 |
+
def make_search_filter(self, username: str) -> str:
|
| 285 |
+
username = ldap3.utils.conv.escape_filter_chars(username)
|
| 286 |
+
return f"({self.filter_key}={username})"
|
| 287 |
+
|
| 288 |
+
def __call__(self, username: str, password: str) -> bool:
|
| 289 |
+
if not username or not password:
|
| 290 |
+
return False
|
| 291 |
+
self.conn.search(self.dn_subtree, self.make_search_filter(username))
|
| 292 |
+
if self.conn.response:
|
| 293 |
+
c = ldap3.Connection(
|
| 294 |
+
self.server, self.conn.response[0]["dn"], password, auto_bind=True
|
| 295 |
+
)
|
| 296 |
+
if c:
|
| 297 |
+
return True
|
| 298 |
+
return False
|
python/user_packages/Python313/site-packages/mitmproxy/addons/proxyserver.py
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This addon is responsible for starting/stopping the proxy server sockets/instances specified by the mode option.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import asyncio
|
| 8 |
+
import collections
|
| 9 |
+
import ipaddress
|
| 10 |
+
import logging
|
| 11 |
+
from collections.abc import Iterable
|
| 12 |
+
from collections.abc import Iterator
|
| 13 |
+
from contextlib import contextmanager
|
| 14 |
+
from typing import Optional
|
| 15 |
+
|
| 16 |
+
from wsproto.frame_protocol import Opcode
|
| 17 |
+
|
| 18 |
+
from mitmproxy import command
|
| 19 |
+
from mitmproxy import ctx
|
| 20 |
+
from mitmproxy import exceptions
|
| 21 |
+
from mitmproxy import http
|
| 22 |
+
from mitmproxy import platform
|
| 23 |
+
from mitmproxy import tcp
|
| 24 |
+
from mitmproxy import udp
|
| 25 |
+
from mitmproxy import websocket
|
| 26 |
+
from mitmproxy.connection import Address
|
| 27 |
+
from mitmproxy.flow import Flow
|
| 28 |
+
from mitmproxy.proxy import events
|
| 29 |
+
from mitmproxy.proxy import mode_specs
|
| 30 |
+
from mitmproxy.proxy import server_hooks
|
| 31 |
+
from mitmproxy.proxy.layers.tcp import TcpMessageInjected
|
| 32 |
+
from mitmproxy.proxy.layers.udp import UdpMessageInjected
|
| 33 |
+
from mitmproxy.proxy.layers.websocket import WebSocketMessageInjected
|
| 34 |
+
from mitmproxy.proxy.mode_servers import ProxyConnectionHandler
|
| 35 |
+
from mitmproxy.proxy.mode_servers import ServerInstance
|
| 36 |
+
from mitmproxy.proxy.mode_servers import ServerManager
|
| 37 |
+
from mitmproxy.utils import asyncio_utils
|
| 38 |
+
from mitmproxy.utils import human
|
| 39 |
+
from mitmproxy.utils import signals
|
| 40 |
+
|
| 41 |
+
logger = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Servers:
|
| 45 |
+
def __init__(self, manager: ServerManager):
|
| 46 |
+
self.changed = signals.AsyncSignal(lambda: None)
|
| 47 |
+
self._instances: dict[mode_specs.ProxyMode, ServerInstance] = dict()
|
| 48 |
+
self._lock = asyncio.Lock()
|
| 49 |
+
self._manager = manager
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def is_updating(self) -> bool:
|
| 53 |
+
return self._lock.locked()
|
| 54 |
+
|
| 55 |
+
async def update(self, modes: Iterable[mode_specs.ProxyMode]) -> bool:
|
| 56 |
+
all_ok = True
|
| 57 |
+
|
| 58 |
+
async with self._lock:
|
| 59 |
+
new_instances: dict[mode_specs.ProxyMode, ServerInstance] = {}
|
| 60 |
+
|
| 61 |
+
start_tasks = []
|
| 62 |
+
if ctx.options.server:
|
| 63 |
+
# Create missing modes and keep existing ones.
|
| 64 |
+
for spec in modes:
|
| 65 |
+
if spec in self._instances:
|
| 66 |
+
instance = self._instances[spec]
|
| 67 |
+
else:
|
| 68 |
+
instance = ServerInstance.make(spec, self._manager)
|
| 69 |
+
start_tasks.append(instance.start())
|
| 70 |
+
new_instances[spec] = instance
|
| 71 |
+
|
| 72 |
+
# Shutdown modes that have been removed from the list.
|
| 73 |
+
stop_tasks = [
|
| 74 |
+
s.stop()
|
| 75 |
+
for spec, s in self._instances.items()
|
| 76 |
+
if spec not in new_instances
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
if not start_tasks and not stop_tasks:
|
| 80 |
+
return (
|
| 81 |
+
True # nothing to do, so we don't need to trigger `self.changed`.
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
self._instances = new_instances
|
| 85 |
+
# Notify listeners about the new not-yet-started servers.
|
| 86 |
+
await self.changed.send()
|
| 87 |
+
|
| 88 |
+
# We first need to free ports before starting new servers.
|
| 89 |
+
for ret in await asyncio.gather(*stop_tasks, return_exceptions=True):
|
| 90 |
+
if ret:
|
| 91 |
+
all_ok = False
|
| 92 |
+
logger.error(str(ret))
|
| 93 |
+
for ret in await asyncio.gather(*start_tasks, return_exceptions=True):
|
| 94 |
+
if ret:
|
| 95 |
+
all_ok = False
|
| 96 |
+
logger.error(str(ret))
|
| 97 |
+
|
| 98 |
+
await self.changed.send()
|
| 99 |
+
return all_ok
|
| 100 |
+
|
| 101 |
+
def __len__(self) -> int:
|
| 102 |
+
return len(self._instances)
|
| 103 |
+
|
| 104 |
+
def __iter__(self) -> Iterator[ServerInstance]:
|
| 105 |
+
return iter(self._instances.values())
|
| 106 |
+
|
| 107 |
+
def __getitem__(self, mode: str | mode_specs.ProxyMode) -> ServerInstance:
|
| 108 |
+
if isinstance(mode, str):
|
| 109 |
+
mode = mode_specs.ProxyMode.parse(mode)
|
| 110 |
+
return self._instances[mode]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class Proxyserver(ServerManager):
|
| 114 |
+
"""
|
| 115 |
+
This addon runs the actual proxy server.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
connections: dict[tuple | str, ProxyConnectionHandler]
|
| 119 |
+
servers: Servers
|
| 120 |
+
|
| 121 |
+
is_running: bool
|
| 122 |
+
_connect_addr: Address | None = None
|
| 123 |
+
|
| 124 |
+
def __init__(self):
|
| 125 |
+
self.connections = {}
|
| 126 |
+
self.servers = Servers(self)
|
| 127 |
+
self.is_running = False
|
| 128 |
+
|
| 129 |
+
def __repr__(self):
|
| 130 |
+
return f"Proxyserver({len(self.connections)} active conns)"
|
| 131 |
+
|
| 132 |
+
@command.command("proxyserver.active_connections")
|
| 133 |
+
def active_connections(self) -> int:
|
| 134 |
+
return len(self.connections)
|
| 135 |
+
|
| 136 |
+
@contextmanager
|
| 137 |
+
def register_connection(
|
| 138 |
+
self, connection_id: tuple | str, handler: ProxyConnectionHandler
|
| 139 |
+
):
|
| 140 |
+
self.connections[connection_id] = handler
|
| 141 |
+
try:
|
| 142 |
+
yield
|
| 143 |
+
finally:
|
| 144 |
+
del self.connections[connection_id]
|
| 145 |
+
|
| 146 |
+
def load(self, loader):
|
| 147 |
+
loader.add_option(
|
| 148 |
+
"store_streamed_bodies",
|
| 149 |
+
bool,
|
| 150 |
+
False,
|
| 151 |
+
"Store HTTP request and response bodies when streamed (see `stream_large_bodies`). "
|
| 152 |
+
"This increases memory consumption, but makes it possible to inspect streamed bodies.",
|
| 153 |
+
)
|
| 154 |
+
loader.add_option(
|
| 155 |
+
"connection_strategy",
|
| 156 |
+
str,
|
| 157 |
+
"eager",
|
| 158 |
+
"Determine when server connections should be established. When set to lazy, mitmproxy "
|
| 159 |
+
"tries to defer establishing an upstream connection as long as possible. This makes it possible to "
|
| 160 |
+
"use server replay while being offline. When set to eager, mitmproxy can detect protocols with "
|
| 161 |
+
"server-side greetings, as well as accurately mirror TLS ALPN negotiation.",
|
| 162 |
+
choices=("eager", "lazy"),
|
| 163 |
+
)
|
| 164 |
+
loader.add_option(
|
| 165 |
+
"stream_large_bodies",
|
| 166 |
+
Optional[str],
|
| 167 |
+
None,
|
| 168 |
+
"""
|
| 169 |
+
Stream data to the client if request or response body exceeds the given
|
| 170 |
+
threshold. If streamed, the body will not be stored in any way,
|
| 171 |
+
and such responses cannot be modified. Understands k/m/g
|
| 172 |
+
suffixes, i.e. 3m for 3 megabytes. To store streamed bodies, see `store_streamed_bodies`.
|
| 173 |
+
""",
|
| 174 |
+
)
|
| 175 |
+
loader.add_option(
|
| 176 |
+
"body_size_limit",
|
| 177 |
+
Optional[str],
|
| 178 |
+
None,
|
| 179 |
+
"""
|
| 180 |
+
Byte size limit of HTTP request and response bodies. Understands
|
| 181 |
+
k/m/g suffixes, i.e. 3m for 3 megabytes.
|
| 182 |
+
""",
|
| 183 |
+
)
|
| 184 |
+
loader.add_option(
|
| 185 |
+
"keep_host_header",
|
| 186 |
+
bool,
|
| 187 |
+
False,
|
| 188 |
+
"""
|
| 189 |
+
Reverse Proxy: Keep the original host header instead of rewriting it
|
| 190 |
+
to the reverse proxy target.
|
| 191 |
+
""",
|
| 192 |
+
)
|
| 193 |
+
loader.add_option(
|
| 194 |
+
"proxy_debug",
|
| 195 |
+
bool,
|
| 196 |
+
False,
|
| 197 |
+
"Enable debug logs in the proxy core.",
|
| 198 |
+
)
|
| 199 |
+
loader.add_option(
|
| 200 |
+
"normalize_outbound_headers",
|
| 201 |
+
bool,
|
| 202 |
+
True,
|
| 203 |
+
"""
|
| 204 |
+
Normalize outgoing HTTP/2 header names, but emit a warning when doing so.
|
| 205 |
+
HTTP/2 does not allow uppercase header names. This option makes sure that HTTP/2 headers set
|
| 206 |
+
in custom scripts are lowercased before they are sent.
|
| 207 |
+
""",
|
| 208 |
+
)
|
| 209 |
+
loader.add_option(
|
| 210 |
+
"validate_inbound_headers",
|
| 211 |
+
bool,
|
| 212 |
+
True,
|
| 213 |
+
"""
|
| 214 |
+
Make sure that incoming HTTP requests are not malformed.
|
| 215 |
+
Disabling this option makes mitmproxy vulnerable to HTTP smuggling attacks.
|
| 216 |
+
""",
|
| 217 |
+
)
|
| 218 |
+
loader.add_option(
|
| 219 |
+
"connect_addr",
|
| 220 |
+
Optional[str],
|
| 221 |
+
None,
|
| 222 |
+
"""Set the local IP address that mitmproxy should use when connecting to upstream servers.""",
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
def running(self):
|
| 226 |
+
self.is_running = True
|
| 227 |
+
|
| 228 |
+
def configure(self, updated) -> None:
|
| 229 |
+
if "stream_large_bodies" in updated:
|
| 230 |
+
try:
|
| 231 |
+
human.parse_size(ctx.options.stream_large_bodies)
|
| 232 |
+
except ValueError:
|
| 233 |
+
raise exceptions.OptionsError(
|
| 234 |
+
f"Invalid stream_large_bodies specification: "
|
| 235 |
+
f"{ctx.options.stream_large_bodies}"
|
| 236 |
+
)
|
| 237 |
+
if "body_size_limit" in updated:
|
| 238 |
+
try:
|
| 239 |
+
human.parse_size(ctx.options.body_size_limit)
|
| 240 |
+
except ValueError:
|
| 241 |
+
raise exceptions.OptionsError(
|
| 242 |
+
f"Invalid body_size_limit specification: "
|
| 243 |
+
f"{ctx.options.body_size_limit}"
|
| 244 |
+
)
|
| 245 |
+
if "connect_addr" in updated:
|
| 246 |
+
try:
|
| 247 |
+
if ctx.options.connect_addr:
|
| 248 |
+
self._connect_addr = (
|
| 249 |
+
str(ipaddress.ip_address(ctx.options.connect_addr)),
|
| 250 |
+
0,
|
| 251 |
+
)
|
| 252 |
+
else:
|
| 253 |
+
self._connect_addr = None
|
| 254 |
+
except ValueError:
|
| 255 |
+
raise exceptions.OptionsError(
|
| 256 |
+
f"Invalid value for connect_addr: {ctx.options.connect_addr!r}. Specify a valid IP address."
|
| 257 |
+
)
|
| 258 |
+
if "mode" in updated or "server" in updated:
|
| 259 |
+
# Make sure that all modes are syntactically valid...
|
| 260 |
+
modes: list[mode_specs.ProxyMode] = []
|
| 261 |
+
for mode in ctx.options.mode:
|
| 262 |
+
try:
|
| 263 |
+
modes.append(mode_specs.ProxyMode.parse(mode))
|
| 264 |
+
except ValueError as e:
|
| 265 |
+
raise exceptions.OptionsError(
|
| 266 |
+
f"Invalid proxy mode specification: {mode} ({e})"
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# ...and don't listen on the same address.
|
| 270 |
+
listen_addrs = []
|
| 271 |
+
for m in modes:
|
| 272 |
+
if m.transport_protocol == "both":
|
| 273 |
+
protocols = ["tcp", "udp"]
|
| 274 |
+
else:
|
| 275 |
+
protocols = [m.transport_protocol]
|
| 276 |
+
host = m.listen_host(ctx.options.listen_host)
|
| 277 |
+
port = m.listen_port(ctx.options.listen_port)
|
| 278 |
+
if port is None:
|
| 279 |
+
continue
|
| 280 |
+
for proto in protocols:
|
| 281 |
+
listen_addrs.append((host, port, proto))
|
| 282 |
+
if len(set(listen_addrs)) != len(listen_addrs):
|
| 283 |
+
(host, port, _) = collections.Counter(listen_addrs).most_common(1)[0][0]
|
| 284 |
+
dup_addr = human.format_address((host or "0.0.0.0", port))
|
| 285 |
+
raise exceptions.OptionsError(
|
| 286 |
+
f"Cannot spawn multiple servers on the same address: {dup_addr}"
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
if ctx.options.mode and not ctx.master.addons.get("nextlayer"):
|
| 290 |
+
logger.warning("Warning: Running proxyserver without nextlayer addon!")
|
| 291 |
+
if any(isinstance(m, mode_specs.TransparentMode) for m in modes):
|
| 292 |
+
if platform.original_addr:
|
| 293 |
+
platform.init_transparent_mode()
|
| 294 |
+
else:
|
| 295 |
+
raise exceptions.OptionsError(
|
| 296 |
+
"Transparent mode not supported on this platform."
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
if self.is_running:
|
| 300 |
+
asyncio_utils.create_task(
|
| 301 |
+
self.servers.update(modes),
|
| 302 |
+
name="update servers",
|
| 303 |
+
keep_ref=True,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
async def setup_servers(self) -> bool:
|
| 307 |
+
"""Setup proxy servers. This may take an indefinite amount of time to complete (e.g. on permission prompts)."""
|
| 308 |
+
return await self.servers.update(
|
| 309 |
+
[mode_specs.ProxyMode.parse(m) for m in ctx.options.mode]
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
def listen_addrs(self) -> list[Address]:
|
| 313 |
+
return [addr for server in self.servers for addr in server.listen_addrs]
|
| 314 |
+
|
| 315 |
+
def inject_event(self, event: events.MessageInjected):
|
| 316 |
+
connection_id: str | tuple
|
| 317 |
+
if event.flow.client_conn.transport_protocol != "udp":
|
| 318 |
+
connection_id = event.flow.client_conn.id
|
| 319 |
+
else: # pragma: no cover
|
| 320 |
+
# temporary workaround: for UDP we don't have persistent client IDs yet.
|
| 321 |
+
connection_id = (
|
| 322 |
+
event.flow.client_conn.peername,
|
| 323 |
+
event.flow.client_conn.sockname,
|
| 324 |
+
)
|
| 325 |
+
if connection_id not in self.connections:
|
| 326 |
+
raise ValueError("Flow is not from a live connection.")
|
| 327 |
+
|
| 328 |
+
asyncio_utils.create_task(
|
| 329 |
+
self.connections[connection_id].server_event(event),
|
| 330 |
+
name=f"inject_event",
|
| 331 |
+
keep_ref=True,
|
| 332 |
+
client=event.flow.client_conn.peername,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@command.command("inject.websocket")
|
| 336 |
+
def inject_websocket(
|
| 337 |
+
self, flow: Flow, to_client: bool, message: bytes, is_text: bool = True
|
| 338 |
+
):
|
| 339 |
+
if not isinstance(flow, http.HTTPFlow) or not flow.websocket:
|
| 340 |
+
logger.warning("Cannot inject WebSocket messages into non-WebSocket flows.")
|
| 341 |
+
return
|
| 342 |
+
|
| 343 |
+
msg = websocket.WebSocketMessage(
|
| 344 |
+
Opcode.TEXT if is_text else Opcode.BINARY, not to_client, message
|
| 345 |
+
)
|
| 346 |
+
event = WebSocketMessageInjected(flow, msg)
|
| 347 |
+
try:
|
| 348 |
+
self.inject_event(event)
|
| 349 |
+
except ValueError as e:
|
| 350 |
+
logger.warning(str(e))
|
| 351 |
+
|
| 352 |
+
@command.command("inject.tcp")
|
| 353 |
+
def inject_tcp(self, flow: Flow, to_client: bool, message: bytes):
|
| 354 |
+
if not isinstance(flow, tcp.TCPFlow):
|
| 355 |
+
logger.warning("Cannot inject TCP messages into non-TCP flows.")
|
| 356 |
+
return
|
| 357 |
+
|
| 358 |
+
event = TcpMessageInjected(flow, tcp.TCPMessage(not to_client, message))
|
| 359 |
+
try:
|
| 360 |
+
self.inject_event(event)
|
| 361 |
+
except ValueError as e:
|
| 362 |
+
logger.warning(str(e))
|
| 363 |
+
|
| 364 |
+
@command.command("inject.udp")
|
| 365 |
+
def inject_udp(self, flow: Flow, to_client: bool, message: bytes):
|
| 366 |
+
if not isinstance(flow, udp.UDPFlow):
|
| 367 |
+
logger.warning("Cannot inject UDP messages into non-UDP flows.")
|
| 368 |
+
return
|
| 369 |
+
|
| 370 |
+
event = UdpMessageInjected(flow, udp.UDPMessage(not to_client, message))
|
| 371 |
+
try:
|
| 372 |
+
self.inject_event(event)
|
| 373 |
+
except ValueError as e:
|
| 374 |
+
logger.warning(str(e))
|
| 375 |
+
|
| 376 |
+
def server_connect(self, data: server_hooks.ServerConnectionHookData):
|
| 377 |
+
if data.server.sockname is None:
|
| 378 |
+
data.server.sockname = self._connect_addr
|
| 379 |
+
|
| 380 |
+
# Prevent mitmproxy from recursively connecting to itself.
|
| 381 |
+
assert data.server.address
|
| 382 |
+
connect_host, connect_port, *_ = data.server.address
|
| 383 |
+
|
| 384 |
+
for server in self.servers:
|
| 385 |
+
for listen_host, listen_port, *_ in server.listen_addrs:
|
| 386 |
+
self_connect = (
|
| 387 |
+
connect_port == listen_port
|
| 388 |
+
and connect_host in ("localhost", "127.0.0.1", "::1", listen_host)
|
| 389 |
+
and server.mode.transport_protocol == data.server.transport_protocol
|
| 390 |
+
)
|
| 391 |
+
if self_connect:
|
| 392 |
+
data.server.error = (
|
| 393 |
+
"Request destination unknown. "
|
| 394 |
+
"Unable to figure out where this request should be forwarded to."
|
| 395 |
+
)
|
| 396 |
+
return
|
python/user_packages/Python313/site-packages/mitmproxy/addons/readfile.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import os.path
|
| 4 |
+
import sys
|
| 5 |
+
from typing import BinaryIO
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
from mitmproxy import command
|
| 9 |
+
from mitmproxy import ctx
|
| 10 |
+
from mitmproxy import exceptions
|
| 11 |
+
from mitmproxy import flowfilter
|
| 12 |
+
from mitmproxy import io
|
| 13 |
+
from mitmproxy.utils import asyncio_utils
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ReadFile:
|
| 19 |
+
"""
|
| 20 |
+
An addon that handles reading from file on startup.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self):
|
| 24 |
+
self.filter = None
|
| 25 |
+
self._read_task: asyncio.Task | None = None
|
| 26 |
+
|
| 27 |
+
def load(self, loader):
|
| 28 |
+
loader.add_option("rfile", Optional[str], None, "Read flows from file.")
|
| 29 |
+
loader.add_option(
|
| 30 |
+
"readfile_filter", Optional[str], None, "Read only matching flows."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
def configure(self, updated):
|
| 34 |
+
if "readfile_filter" in updated:
|
| 35 |
+
if ctx.options.readfile_filter:
|
| 36 |
+
try:
|
| 37 |
+
self.filter = flowfilter.parse(ctx.options.readfile_filter)
|
| 38 |
+
except ValueError as e:
|
| 39 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 40 |
+
else:
|
| 41 |
+
self.filter = None
|
| 42 |
+
|
| 43 |
+
async def load_flows(self, fo: BinaryIO) -> int:
|
| 44 |
+
cnt = 0
|
| 45 |
+
freader = io.FlowReader(fo)
|
| 46 |
+
try:
|
| 47 |
+
for flow in freader.stream():
|
| 48 |
+
if self.filter and not self.filter(flow):
|
| 49 |
+
continue
|
| 50 |
+
await ctx.master.load_flow(flow)
|
| 51 |
+
cnt += 1
|
| 52 |
+
except (OSError, exceptions.FlowReadException) as e:
|
| 53 |
+
if cnt:
|
| 54 |
+
logging.warning("Flow file corrupted - loaded %i flows." % cnt)
|
| 55 |
+
else:
|
| 56 |
+
logging.error("Flow file corrupted.")
|
| 57 |
+
raise exceptions.FlowReadException(str(e)) from e
|
| 58 |
+
else:
|
| 59 |
+
return cnt
|
| 60 |
+
|
| 61 |
+
async def load_flows_from_path(self, path: str) -> int:
|
| 62 |
+
path = os.path.expanduser(path)
|
| 63 |
+
try:
|
| 64 |
+
with open(path, "rb") as f:
|
| 65 |
+
return await self.load_flows(f)
|
| 66 |
+
except OSError as e:
|
| 67 |
+
logging.error(f"Cannot load flows: {e}")
|
| 68 |
+
raise exceptions.FlowReadException(str(e)) from e
|
| 69 |
+
|
| 70 |
+
async def doread(self, rfile: str) -> None:
|
| 71 |
+
try:
|
| 72 |
+
await self.load_flows_from_path(rfile)
|
| 73 |
+
except exceptions.FlowReadException as e:
|
| 74 |
+
logger.exception(f"Failed to read {ctx.options.rfile}: {e}")
|
| 75 |
+
|
| 76 |
+
def running(self):
|
| 77 |
+
if ctx.options.rfile:
|
| 78 |
+
self._read_task = asyncio_utils.create_task(
|
| 79 |
+
self.doread(ctx.options.rfile),
|
| 80 |
+
name="readfile",
|
| 81 |
+
keep_ref=False,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
@command.command("readfile.reading")
|
| 85 |
+
def reading(self) -> bool:
|
| 86 |
+
return bool(self._read_task and not self._read_task.done())
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class ReadFileStdin(ReadFile):
|
| 90 |
+
"""Support the special case of "-" for reading from stdin"""
|
| 91 |
+
|
| 92 |
+
async def load_flows_from_path(self, path: str) -> int:
|
| 93 |
+
if path == "-": # pragma: no cover
|
| 94 |
+
# Need to think about how to test this. This function is scheduled
|
| 95 |
+
# onto the event loop, where a sys.stdin mock has no effect.
|
| 96 |
+
return await self.load_flows(sys.stdin.buffer)
|
| 97 |
+
else:
|
| 98 |
+
return await super().load_flows_from_path(path)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/save.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os.path
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Literal
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
import mitmproxy.types
|
| 12 |
+
from mitmproxy import command
|
| 13 |
+
from mitmproxy import ctx
|
| 14 |
+
from mitmproxy import dns
|
| 15 |
+
from mitmproxy import exceptions
|
| 16 |
+
from mitmproxy import flow
|
| 17 |
+
from mitmproxy import flowfilter
|
| 18 |
+
from mitmproxy import http
|
| 19 |
+
from mitmproxy import io
|
| 20 |
+
from mitmproxy import tcp
|
| 21 |
+
from mitmproxy import udp
|
| 22 |
+
from mitmproxy.log import ALERT
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@lru_cache
|
| 26 |
+
def _path(path: str) -> str:
|
| 27 |
+
"""Extract the path from a path spec (which may have an extra "+" at the front)"""
|
| 28 |
+
if path.startswith("+"):
|
| 29 |
+
path = path[1:]
|
| 30 |
+
return os.path.expanduser(path)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@lru_cache
|
| 34 |
+
def _mode(path: str) -> Literal["ab", "wb"]:
|
| 35 |
+
"""Extract the writing mode (overwrite or append) from a path spec"""
|
| 36 |
+
if path.startswith("+"):
|
| 37 |
+
return "ab"
|
| 38 |
+
else:
|
| 39 |
+
return "wb"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Save:
|
| 43 |
+
def __init__(self) -> None:
|
| 44 |
+
self.stream: io.FilteredFlowWriter | None = None
|
| 45 |
+
self.filt: flowfilter.TFilter | None = None
|
| 46 |
+
self.active_flows: set[flow.Flow] = set()
|
| 47 |
+
self.current_path: str | None = None
|
| 48 |
+
|
| 49 |
+
def load(self, loader):
|
| 50 |
+
loader.add_option(
|
| 51 |
+
"save_stream_file",
|
| 52 |
+
Optional[str],
|
| 53 |
+
None,
|
| 54 |
+
"""
|
| 55 |
+
Stream flows to file as they arrive. Prefix path with + to append.
|
| 56 |
+
The full path can use python strftime() formating, missing
|
| 57 |
+
directories are created as needed. A new file is opened every time
|
| 58 |
+
the formatted string changes.
|
| 59 |
+
""",
|
| 60 |
+
)
|
| 61 |
+
loader.add_option(
|
| 62 |
+
"save_stream_filter",
|
| 63 |
+
Optional[str],
|
| 64 |
+
None,
|
| 65 |
+
"Filter which flows are written to file.",
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
def configure(self, updated):
|
| 69 |
+
if "save_stream_filter" in updated:
|
| 70 |
+
if ctx.options.save_stream_filter:
|
| 71 |
+
try:
|
| 72 |
+
self.filt = flowfilter.parse(ctx.options.save_stream_filter)
|
| 73 |
+
except ValueError as e:
|
| 74 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 75 |
+
else:
|
| 76 |
+
self.filt = None
|
| 77 |
+
if "save_stream_file" in updated or "save_stream_filter" in updated:
|
| 78 |
+
if ctx.options.save_stream_file:
|
| 79 |
+
try:
|
| 80 |
+
self.maybe_rotate_to_new_file()
|
| 81 |
+
except OSError as e:
|
| 82 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 83 |
+
assert self.stream
|
| 84 |
+
self.stream.flt = self.filt
|
| 85 |
+
else:
|
| 86 |
+
self.done()
|
| 87 |
+
|
| 88 |
+
def maybe_rotate_to_new_file(self) -> None:
|
| 89 |
+
path = datetime.today().strftime(_path(ctx.options.save_stream_file))
|
| 90 |
+
if self.current_path == path:
|
| 91 |
+
return
|
| 92 |
+
|
| 93 |
+
if self.stream:
|
| 94 |
+
self.stream.fo.close()
|
| 95 |
+
self.stream = None
|
| 96 |
+
|
| 97 |
+
new_log_file = Path(path)
|
| 98 |
+
new_log_file.parent.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
|
| 100 |
+
f = new_log_file.open(_mode(ctx.options.save_stream_file))
|
| 101 |
+
self.stream = io.FilteredFlowWriter(f, self.filt)
|
| 102 |
+
self.current_path = path
|
| 103 |
+
|
| 104 |
+
def save_flow(self, flow: flow.Flow) -> None:
|
| 105 |
+
"""
|
| 106 |
+
Write the flow to the stream, but first check if we need to rotate to a new file.
|
| 107 |
+
"""
|
| 108 |
+
if not self.stream:
|
| 109 |
+
return
|
| 110 |
+
try:
|
| 111 |
+
self.maybe_rotate_to_new_file()
|
| 112 |
+
self.stream.add(flow)
|
| 113 |
+
except OSError as e:
|
| 114 |
+
# If we somehow fail to write flows to a logfile, we really want to crash visibly
|
| 115 |
+
# instead of letting traffic through unrecorded.
|
| 116 |
+
# No normal logging here, that would not be triggered anymore.
|
| 117 |
+
sys.stderr.write(f"Error while writing to {self.current_path}: {e}")
|
| 118 |
+
sys.exit(1)
|
| 119 |
+
else:
|
| 120 |
+
self.active_flows.discard(flow)
|
| 121 |
+
|
| 122 |
+
def done(self) -> None:
|
| 123 |
+
if self.stream:
|
| 124 |
+
for f in self.active_flows:
|
| 125 |
+
self.stream.add(f)
|
| 126 |
+
self.active_flows.clear()
|
| 127 |
+
|
| 128 |
+
self.current_path = None
|
| 129 |
+
self.stream.fo.close()
|
| 130 |
+
self.stream = None
|
| 131 |
+
|
| 132 |
+
@command.command("save.file")
|
| 133 |
+
def save(self, flows: Sequence[flow.Flow], path: mitmproxy.types.Path) -> None:
|
| 134 |
+
"""
|
| 135 |
+
Save flows to a file. If the path starts with a +, flows are
|
| 136 |
+
appended to the file, otherwise it is over-written.
|
| 137 |
+
"""
|
| 138 |
+
try:
|
| 139 |
+
with open(_path(path), _mode(path)) as f:
|
| 140 |
+
stream = io.FlowWriter(f)
|
| 141 |
+
for i in flows:
|
| 142 |
+
stream.add(i)
|
| 143 |
+
except OSError as e:
|
| 144 |
+
raise exceptions.CommandError(e) from e
|
| 145 |
+
if path.endswith(".har") or path.endswith(".zhar"): # pragma: no cover
|
| 146 |
+
logging.log(
|
| 147 |
+
ALERT,
|
| 148 |
+
f"Saved as mitmproxy dump file. To save HAR files, use the `save.har` command.",
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
logging.log(ALERT, f"Saved {len(flows)} flows.")
|
| 152 |
+
|
| 153 |
+
def tcp_start(self, flow: tcp.TCPFlow):
|
| 154 |
+
if self.stream:
|
| 155 |
+
self.active_flows.add(flow)
|
| 156 |
+
|
| 157 |
+
def tcp_end(self, flow: tcp.TCPFlow):
|
| 158 |
+
self.save_flow(flow)
|
| 159 |
+
|
| 160 |
+
def tcp_error(self, flow: tcp.TCPFlow):
|
| 161 |
+
self.tcp_end(flow)
|
| 162 |
+
|
| 163 |
+
def udp_start(self, flow: udp.UDPFlow):
|
| 164 |
+
if self.stream:
|
| 165 |
+
self.active_flows.add(flow)
|
| 166 |
+
|
| 167 |
+
def udp_end(self, flow: udp.UDPFlow):
|
| 168 |
+
self.save_flow(flow)
|
| 169 |
+
|
| 170 |
+
def udp_error(self, flow: udp.UDPFlow):
|
| 171 |
+
self.udp_end(flow)
|
| 172 |
+
|
| 173 |
+
def websocket_end(self, flow: http.HTTPFlow):
|
| 174 |
+
self.save_flow(flow)
|
| 175 |
+
|
| 176 |
+
def request(self, flow: http.HTTPFlow):
|
| 177 |
+
if self.stream:
|
| 178 |
+
self.active_flows.add(flow)
|
| 179 |
+
|
| 180 |
+
def response(self, flow: http.HTTPFlow):
|
| 181 |
+
# websocket flows will receive a websocket_end,
|
| 182 |
+
# we don't want to persist them here already
|
| 183 |
+
if flow.websocket is None:
|
| 184 |
+
self.save_flow(flow)
|
| 185 |
+
|
| 186 |
+
def error(self, flow: http.HTTPFlow):
|
| 187 |
+
self.response(flow)
|
| 188 |
+
|
| 189 |
+
def dns_request(self, flow: dns.DNSFlow):
|
| 190 |
+
if self.stream:
|
| 191 |
+
self.active_flows.add(flow)
|
| 192 |
+
|
| 193 |
+
def dns_response(self, flow: dns.DNSFlow):
|
| 194 |
+
self.save_flow(flow)
|
| 195 |
+
|
| 196 |
+
def dns_error(self, flow: dns.DNSFlow):
|
| 197 |
+
self.save_flow(flow)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/savehar.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write flow objects to a HAR file"""
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import zlib
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from datetime import timezone
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from mitmproxy import command
|
| 13 |
+
from mitmproxy import ctx
|
| 14 |
+
from mitmproxy import exceptions
|
| 15 |
+
from mitmproxy import flow
|
| 16 |
+
from mitmproxy import flowfilter
|
| 17 |
+
from mitmproxy import http
|
| 18 |
+
from mitmproxy import types
|
| 19 |
+
from mitmproxy import version
|
| 20 |
+
from mitmproxy.addonmanager import Loader
|
| 21 |
+
from mitmproxy.connection import Server
|
| 22 |
+
from mitmproxy.coretypes.multidict import _MultiDict
|
| 23 |
+
from mitmproxy.log import ALERT
|
| 24 |
+
from mitmproxy.utils import human
|
| 25 |
+
from mitmproxy.utils import strutils
|
| 26 |
+
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SaveHar:
|
| 31 |
+
def __init__(self) -> None:
|
| 32 |
+
self.flows: list[flow.Flow] = []
|
| 33 |
+
self.filt: flowfilter.TFilter | None = None
|
| 34 |
+
|
| 35 |
+
@command.command("save.har")
|
| 36 |
+
def export_har(self, flows: Sequence[flow.Flow], path: types.Path) -> None:
|
| 37 |
+
"""Export flows to an HAR (HTTP Archive) file."""
|
| 38 |
+
|
| 39 |
+
har = json.dumps(self.make_har(flows), indent=4).encode()
|
| 40 |
+
|
| 41 |
+
if path.endswith(".zhar"):
|
| 42 |
+
har = zlib.compress(har, 9)
|
| 43 |
+
|
| 44 |
+
with open(path, "wb") as f:
|
| 45 |
+
f.write(har)
|
| 46 |
+
|
| 47 |
+
logging.log(ALERT, f"HAR file saved ({human.pretty_size(len(har))} bytes).")
|
| 48 |
+
|
| 49 |
+
def make_har(self, flows: Sequence[flow.Flow]) -> dict:
|
| 50 |
+
entries = []
|
| 51 |
+
skipped = 0
|
| 52 |
+
# A list of server seen till now is maintained so we can avoid
|
| 53 |
+
# using 'connect' time for entries that use an existing connection.
|
| 54 |
+
servers_seen: set[Server] = set()
|
| 55 |
+
|
| 56 |
+
for f in flows:
|
| 57 |
+
if isinstance(f, http.HTTPFlow):
|
| 58 |
+
entries.append(self.flow_entry(f, servers_seen))
|
| 59 |
+
else:
|
| 60 |
+
skipped += 1
|
| 61 |
+
|
| 62 |
+
if skipped > 0:
|
| 63 |
+
logger.info(f"Skipped {skipped} flows that weren't HTTP flows.")
|
| 64 |
+
|
| 65 |
+
return {
|
| 66 |
+
"log": {
|
| 67 |
+
"version": "1.2",
|
| 68 |
+
"creator": {
|
| 69 |
+
"name": "mitmproxy",
|
| 70 |
+
"version": version.VERSION,
|
| 71 |
+
"comment": "",
|
| 72 |
+
},
|
| 73 |
+
"pages": [],
|
| 74 |
+
"entries": entries,
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
def load(self, loader: Loader):
|
| 79 |
+
loader.add_option(
|
| 80 |
+
"hardump",
|
| 81 |
+
str,
|
| 82 |
+
"",
|
| 83 |
+
"""
|
| 84 |
+
Save a HAR file with all flows on exit.
|
| 85 |
+
You may select particular flows by setting save_stream_filter.
|
| 86 |
+
For mitmdump, enabling this option will mean that flows are kept in memory.
|
| 87 |
+
""",
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def configure(self, updated):
|
| 91 |
+
if "save_stream_filter" in updated:
|
| 92 |
+
if ctx.options.save_stream_filter:
|
| 93 |
+
try:
|
| 94 |
+
self.filt = flowfilter.parse(ctx.options.save_stream_filter)
|
| 95 |
+
except ValueError as e:
|
| 96 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 97 |
+
else:
|
| 98 |
+
self.filt = None
|
| 99 |
+
|
| 100 |
+
if "hardump" in updated:
|
| 101 |
+
if not ctx.options.hardump:
|
| 102 |
+
self.flows = []
|
| 103 |
+
|
| 104 |
+
def response(self, flow: http.HTTPFlow) -> None:
|
| 105 |
+
# websocket flows will receive a websocket_end,
|
| 106 |
+
# we don't want to persist them here already
|
| 107 |
+
if flow.websocket is None:
|
| 108 |
+
self._save_flow(flow)
|
| 109 |
+
|
| 110 |
+
def error(self, flow: http.HTTPFlow) -> None:
|
| 111 |
+
self.response(flow)
|
| 112 |
+
|
| 113 |
+
def websocket_end(self, flow: http.HTTPFlow) -> None:
|
| 114 |
+
self._save_flow(flow)
|
| 115 |
+
|
| 116 |
+
def _save_flow(self, flow: http.HTTPFlow) -> None:
|
| 117 |
+
if ctx.options.hardump:
|
| 118 |
+
flow_matches = self.filt is None or self.filt(flow)
|
| 119 |
+
if flow_matches:
|
| 120 |
+
self.flows.append(flow)
|
| 121 |
+
|
| 122 |
+
def done(self):
|
| 123 |
+
if ctx.options.hardump:
|
| 124 |
+
if ctx.options.hardump == "-":
|
| 125 |
+
har = self.make_har(self.flows)
|
| 126 |
+
print(json.dumps(har, indent=4))
|
| 127 |
+
else:
|
| 128 |
+
self.export_har(self.flows, ctx.options.hardump)
|
| 129 |
+
|
| 130 |
+
def flow_entry(self, flow: http.HTTPFlow, servers_seen: set[Server]) -> dict:
|
| 131 |
+
"""Creates HAR entry from flow"""
|
| 132 |
+
|
| 133 |
+
if flow.server_conn in servers_seen:
|
| 134 |
+
connect_time = -1.0
|
| 135 |
+
ssl_time = -1.0
|
| 136 |
+
elif flow.server_conn.timestamp_tcp_setup:
|
| 137 |
+
assert flow.server_conn.timestamp_start
|
| 138 |
+
connect_time = 1000 * (
|
| 139 |
+
flow.server_conn.timestamp_tcp_setup - flow.server_conn.timestamp_start
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
if flow.server_conn.timestamp_tls_setup:
|
| 143 |
+
ssl_time = 1000 * (
|
| 144 |
+
flow.server_conn.timestamp_tls_setup
|
| 145 |
+
- flow.server_conn.timestamp_tcp_setup
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
ssl_time = -1.0
|
| 149 |
+
servers_seen.add(flow.server_conn)
|
| 150 |
+
else:
|
| 151 |
+
connect_time = -1.0
|
| 152 |
+
ssl_time = -1.0
|
| 153 |
+
|
| 154 |
+
if flow.request.timestamp_end:
|
| 155 |
+
send = 1000 * (flow.request.timestamp_end - flow.request.timestamp_start)
|
| 156 |
+
else:
|
| 157 |
+
send = 0
|
| 158 |
+
|
| 159 |
+
if flow.response and flow.request.timestamp_end:
|
| 160 |
+
wait = 1000 * (flow.response.timestamp_start - flow.request.timestamp_end)
|
| 161 |
+
else:
|
| 162 |
+
wait = 0
|
| 163 |
+
|
| 164 |
+
if flow.response and flow.response.timestamp_end:
|
| 165 |
+
receive = 1000 * (
|
| 166 |
+
flow.response.timestamp_end - flow.response.timestamp_start
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
else:
|
| 170 |
+
receive = 0
|
| 171 |
+
|
| 172 |
+
timings: dict[str, float | None] = {
|
| 173 |
+
"connect": connect_time,
|
| 174 |
+
"ssl": ssl_time,
|
| 175 |
+
"send": send,
|
| 176 |
+
"receive": receive,
|
| 177 |
+
"wait": wait,
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
if flow.response:
|
| 181 |
+
try:
|
| 182 |
+
content = flow.response.content
|
| 183 |
+
except ValueError:
|
| 184 |
+
content = flow.response.raw_content
|
| 185 |
+
response_body_size = (
|
| 186 |
+
len(flow.response.raw_content) if flow.response.raw_content else 0
|
| 187 |
+
)
|
| 188 |
+
response_body_decoded_size = len(content) if content else 0
|
| 189 |
+
response_body_compression = response_body_decoded_size - response_body_size
|
| 190 |
+
response = {
|
| 191 |
+
"status": flow.response.status_code,
|
| 192 |
+
"statusText": flow.response.reason,
|
| 193 |
+
"httpVersion": flow.response.http_version,
|
| 194 |
+
"cookies": self.format_response_cookies(flow.response),
|
| 195 |
+
"headers": self.format_multidict(flow.response.headers),
|
| 196 |
+
"content": {
|
| 197 |
+
"size": response_body_size,
|
| 198 |
+
"compression": response_body_compression,
|
| 199 |
+
"mimeType": flow.response.headers.get("Content-Type", ""),
|
| 200 |
+
},
|
| 201 |
+
"redirectURL": flow.response.headers.get("Location", ""),
|
| 202 |
+
"headersSize": len(str(flow.response.headers)),
|
| 203 |
+
"bodySize": response_body_size,
|
| 204 |
+
}
|
| 205 |
+
if content and strutils.is_mostly_bin(content):
|
| 206 |
+
response["content"]["text"] = base64.b64encode(content).decode()
|
| 207 |
+
response["content"]["encoding"] = "base64"
|
| 208 |
+
else:
|
| 209 |
+
text_content = flow.response.get_text(strict=False)
|
| 210 |
+
if text_content is None:
|
| 211 |
+
response["content"]["text"] = ""
|
| 212 |
+
else:
|
| 213 |
+
response["content"]["text"] = text_content
|
| 214 |
+
else:
|
| 215 |
+
response = {
|
| 216 |
+
"status": 0,
|
| 217 |
+
"statusText": "",
|
| 218 |
+
"httpVersion": "",
|
| 219 |
+
"headers": [],
|
| 220 |
+
"cookies": [],
|
| 221 |
+
"content": {},
|
| 222 |
+
"redirectURL": "",
|
| 223 |
+
"headersSize": -1,
|
| 224 |
+
"bodySize": -1,
|
| 225 |
+
"_transferSize": 0,
|
| 226 |
+
"_error": None,
|
| 227 |
+
}
|
| 228 |
+
if flow.error:
|
| 229 |
+
response["_error"] = flow.error.msg
|
| 230 |
+
|
| 231 |
+
if flow.request.method == "CONNECT":
|
| 232 |
+
url = f"https://{flow.request.pretty_url}/"
|
| 233 |
+
else:
|
| 234 |
+
url = flow.request.pretty_url
|
| 235 |
+
|
| 236 |
+
entry: dict[str, Any] = {
|
| 237 |
+
"startedDateTime": datetime.fromtimestamp(
|
| 238 |
+
flow.request.timestamp_start, timezone.utc
|
| 239 |
+
).isoformat(),
|
| 240 |
+
"time": sum(v for v in timings.values() if v is not None and v >= 0),
|
| 241 |
+
"request": {
|
| 242 |
+
"method": flow.request.method,
|
| 243 |
+
"url": url,
|
| 244 |
+
"httpVersion": flow.request.http_version,
|
| 245 |
+
"cookies": self.format_multidict(flow.request.cookies),
|
| 246 |
+
"headers": self.format_multidict(flow.request.headers),
|
| 247 |
+
"queryString": self.format_multidict(flow.request.query),
|
| 248 |
+
"headersSize": len(str(flow.request.headers)),
|
| 249 |
+
"bodySize": len(flow.request.raw_content)
|
| 250 |
+
if flow.request.raw_content
|
| 251 |
+
else 0,
|
| 252 |
+
},
|
| 253 |
+
"response": response,
|
| 254 |
+
"cache": {},
|
| 255 |
+
"timings": timings,
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
if flow.request.method in ["POST", "PUT", "PATCH"]:
|
| 259 |
+
params = self.format_multidict(flow.request.urlencoded_form)
|
| 260 |
+
entry["request"]["postData"] = {
|
| 261 |
+
"mimeType": flow.request.headers.get("Content-Type", ""),
|
| 262 |
+
"text": flow.request.get_text(strict=False),
|
| 263 |
+
"params": params,
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
if flow.server_conn.peername:
|
| 267 |
+
entry["serverIPAddress"] = str(flow.server_conn.peername[0])
|
| 268 |
+
|
| 269 |
+
websocket_messages = []
|
| 270 |
+
if flow.websocket:
|
| 271 |
+
for message in flow.websocket.messages:
|
| 272 |
+
if message.is_text:
|
| 273 |
+
data = message.text
|
| 274 |
+
else:
|
| 275 |
+
data = base64.b64encode(message.content).decode()
|
| 276 |
+
websocket_message = {
|
| 277 |
+
"type": "send" if message.from_client else "receive",
|
| 278 |
+
"time": message.timestamp,
|
| 279 |
+
"opcode": message.type.value,
|
| 280 |
+
"data": data,
|
| 281 |
+
}
|
| 282 |
+
websocket_messages.append(websocket_message)
|
| 283 |
+
|
| 284 |
+
entry["_resourceType"] = "websocket"
|
| 285 |
+
entry["_webSocketMessages"] = websocket_messages
|
| 286 |
+
return entry
|
| 287 |
+
|
| 288 |
+
def format_response_cookies(self, response: http.Response) -> list[dict]:
|
| 289 |
+
"""Formats the response's cookie header to list of cookies"""
|
| 290 |
+
cookie_list = response.cookies.items(multi=True)
|
| 291 |
+
rv = []
|
| 292 |
+
for name, (value, attrs) in cookie_list:
|
| 293 |
+
cookie = {
|
| 294 |
+
"name": name,
|
| 295 |
+
"value": value,
|
| 296 |
+
"path": attrs.get("path", "/"),
|
| 297 |
+
"domain": attrs.get("domain", ""),
|
| 298 |
+
"httpOnly": "httpOnly" in attrs,
|
| 299 |
+
"secure": "secure" in attrs,
|
| 300 |
+
}
|
| 301 |
+
# TODO: handle expires attribute here.
|
| 302 |
+
# This is not quite trivial because we need to parse random date formats.
|
| 303 |
+
# For now, we just ignore the attribute.
|
| 304 |
+
|
| 305 |
+
if "sameSite" in attrs:
|
| 306 |
+
cookie["sameSite"] = attrs["sameSite"]
|
| 307 |
+
|
| 308 |
+
rv.append(cookie)
|
| 309 |
+
return rv
|
| 310 |
+
|
| 311 |
+
def format_multidict(self, obj: _MultiDict[str, str]) -> list[dict]:
|
| 312 |
+
return [{"name": k, "value": v} for k, v in obj.items(multi=True)]
|
python/user_packages/Python313/site-packages/mitmproxy/addons/script.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import importlib.machinery
|
| 3 |
+
import importlib.util
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import types
|
| 8 |
+
from collections.abc import Sequence
|
| 9 |
+
|
| 10 |
+
import mitmproxy.types as mtypes
|
| 11 |
+
from mitmproxy import addonmanager
|
| 12 |
+
from mitmproxy import command
|
| 13 |
+
from mitmproxy import ctx
|
| 14 |
+
from mitmproxy import eventsequence
|
| 15 |
+
from mitmproxy import exceptions
|
| 16 |
+
from mitmproxy import flow
|
| 17 |
+
from mitmproxy import hooks
|
| 18 |
+
from mitmproxy.utils import asyncio_utils
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_script(path: str) -> types.ModuleType | None:
|
| 24 |
+
fullname = "__mitmproxy_script__.{}".format(
|
| 25 |
+
os.path.splitext(os.path.basename(path))[0]
|
| 26 |
+
)
|
| 27 |
+
# the fullname is not unique among scripts, so if there already is an existing script with said
|
| 28 |
+
# fullname, remove it.
|
| 29 |
+
sys.modules.pop(fullname, None)
|
| 30 |
+
oldpath = sys.path
|
| 31 |
+
sys.path.insert(0, os.path.dirname(path))
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
loader = importlib.machinery.SourceFileLoader(fullname, path)
|
| 35 |
+
spec = importlib.util.spec_from_loader(fullname, loader=loader)
|
| 36 |
+
assert spec
|
| 37 |
+
m = importlib.util.module_from_spec(spec)
|
| 38 |
+
loader.exec_module(m)
|
| 39 |
+
if not getattr(m, "name", None):
|
| 40 |
+
m.name = path # type: ignore
|
| 41 |
+
return m
|
| 42 |
+
except ImportError as e:
|
| 43 |
+
if getattr(sys, "frozen", False):
|
| 44 |
+
e.msg += (
|
| 45 |
+
f".\n"
|
| 46 |
+
f"Note that mitmproxy's binaries include their own Python environment. "
|
| 47 |
+
f"If your addon requires the installation of additional dependencies, "
|
| 48 |
+
f"please install mitmproxy from PyPI "
|
| 49 |
+
f"(https://docs.mitmproxy.org/stable/overview-installation/#installation-from-the-python-package-index-pypi)."
|
| 50 |
+
)
|
| 51 |
+
script_error_handler(path, e)
|
| 52 |
+
return None
|
| 53 |
+
except Exception as e:
|
| 54 |
+
script_error_handler(path, e)
|
| 55 |
+
return None
|
| 56 |
+
finally:
|
| 57 |
+
sys.path[:] = oldpath
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def script_error_handler(path: str, exc: Exception) -> None:
|
| 61 |
+
"""
|
| 62 |
+
Log errors during script loading.
|
| 63 |
+
"""
|
| 64 |
+
tback = exc.__traceback__
|
| 65 |
+
tback = addonmanager.cut_traceback(
|
| 66 |
+
tback, "invoke_addon_sync"
|
| 67 |
+
) # we're calling configure() on load
|
| 68 |
+
tback = addonmanager.cut_traceback(
|
| 69 |
+
tback, "_call_with_frames_removed"
|
| 70 |
+
) # module execution from importlib
|
| 71 |
+
logger.error(f"error in script {path}", exc_info=(type(exc), exc, tback))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
ReloadInterval = 1
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Script:
|
| 78 |
+
"""
|
| 79 |
+
An addon that manages a single script.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, path: str, reload: bool) -> None:
|
| 83 |
+
self.name = "scriptmanager:" + path
|
| 84 |
+
self.path = path
|
| 85 |
+
self.fullpath = os.path.expanduser(path.strip("'\" "))
|
| 86 |
+
self.ns: types.ModuleType | None = None
|
| 87 |
+
self.is_running = False
|
| 88 |
+
|
| 89 |
+
if not os.path.isfile(self.fullpath):
|
| 90 |
+
raise exceptions.OptionsError(f"No such script: {self.fullpath}")
|
| 91 |
+
|
| 92 |
+
self.reloadtask = None
|
| 93 |
+
if reload:
|
| 94 |
+
self.reloadtask = asyncio_utils.create_task(
|
| 95 |
+
self.watcher(),
|
| 96 |
+
name=f"script watcher for {path}",
|
| 97 |
+
keep_ref=False,
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
self.loadscript()
|
| 101 |
+
|
| 102 |
+
def running(self):
|
| 103 |
+
self.is_running = True
|
| 104 |
+
|
| 105 |
+
def done(self):
|
| 106 |
+
if self.reloadtask:
|
| 107 |
+
self.reloadtask.cancel()
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def addons(self):
|
| 111 |
+
return [self.ns] if self.ns else []
|
| 112 |
+
|
| 113 |
+
def loadscript(self):
|
| 114 |
+
logger.info("Loading script %s" % self.path)
|
| 115 |
+
if self.ns:
|
| 116 |
+
ctx.master.addons.remove(self.ns)
|
| 117 |
+
self.ns = None
|
| 118 |
+
with addonmanager.safecall():
|
| 119 |
+
ns = load_script(self.fullpath)
|
| 120 |
+
ctx.master.addons.register(ns)
|
| 121 |
+
self.ns = ns
|
| 122 |
+
if self.ns:
|
| 123 |
+
try:
|
| 124 |
+
ctx.master.addons.invoke_addon_sync(
|
| 125 |
+
self.ns, hooks.ConfigureHook(ctx.options.keys())
|
| 126 |
+
)
|
| 127 |
+
except Exception as e:
|
| 128 |
+
script_error_handler(self.fullpath, e)
|
| 129 |
+
if self.is_running:
|
| 130 |
+
# We're already running, so we call that on the addon now.
|
| 131 |
+
ctx.master.addons.invoke_addon_sync(self.ns, hooks.RunningHook())
|
| 132 |
+
|
| 133 |
+
async def watcher(self):
|
| 134 |
+
# Script loading is terminally confused at the moment.
|
| 135 |
+
# This here is a stopgap workaround to defer loading.
|
| 136 |
+
await asyncio.sleep(0)
|
| 137 |
+
last_mtime = 0.0
|
| 138 |
+
while True:
|
| 139 |
+
try:
|
| 140 |
+
mtime = os.stat(self.fullpath).st_mtime
|
| 141 |
+
except FileNotFoundError:
|
| 142 |
+
logger.info("Removing script %s" % self.path)
|
| 143 |
+
scripts = list(ctx.options.scripts)
|
| 144 |
+
scripts.remove(self.path)
|
| 145 |
+
ctx.options.update(scripts=scripts)
|
| 146 |
+
return
|
| 147 |
+
if mtime > last_mtime:
|
| 148 |
+
self.loadscript()
|
| 149 |
+
last_mtime = mtime
|
| 150 |
+
await asyncio.sleep(ReloadInterval)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class ScriptLoader:
|
| 154 |
+
"""
|
| 155 |
+
An addon that manages loading scripts from options.
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
def __init__(self):
|
| 159 |
+
self.is_running = False
|
| 160 |
+
self.addons = []
|
| 161 |
+
|
| 162 |
+
def load(self, loader):
|
| 163 |
+
loader.add_option("scripts", Sequence[str], [], "Execute a script.")
|
| 164 |
+
|
| 165 |
+
def running(self):
|
| 166 |
+
self.is_running = True
|
| 167 |
+
|
| 168 |
+
@command.command("script.run")
|
| 169 |
+
def script_run(self, flows: Sequence[flow.Flow], path: mtypes.Path) -> None:
|
| 170 |
+
"""
|
| 171 |
+
Run a script on the specified flows. The script is configured with
|
| 172 |
+
the current options and all lifecycle events for each flow are
|
| 173 |
+
simulated. Note that the load event is not invoked.
|
| 174 |
+
"""
|
| 175 |
+
if not os.path.isfile(path):
|
| 176 |
+
logger.error("No such script: %s" % path)
|
| 177 |
+
return
|
| 178 |
+
mod = load_script(path)
|
| 179 |
+
if mod:
|
| 180 |
+
with addonmanager.safecall():
|
| 181 |
+
ctx.master.addons.invoke_addon_sync(
|
| 182 |
+
mod,
|
| 183 |
+
hooks.ConfigureHook(ctx.options.keys()),
|
| 184 |
+
)
|
| 185 |
+
ctx.master.addons.invoke_addon_sync(mod, hooks.RunningHook())
|
| 186 |
+
for f in flows:
|
| 187 |
+
for evt in eventsequence.iterate(f):
|
| 188 |
+
ctx.master.addons.invoke_addon_sync(mod, evt)
|
| 189 |
+
|
| 190 |
+
def configure(self, updated):
|
| 191 |
+
if "scripts" in updated:
|
| 192 |
+
for s in ctx.options.scripts:
|
| 193 |
+
if ctx.options.scripts.count(s) > 1:
|
| 194 |
+
raise exceptions.OptionsError("Duplicate script")
|
| 195 |
+
|
| 196 |
+
for a in self.addons[:]:
|
| 197 |
+
if a.path not in ctx.options.scripts:
|
| 198 |
+
logger.info("Un-loading script: %s" % a.path)
|
| 199 |
+
ctx.master.addons.remove(a)
|
| 200 |
+
self.addons.remove(a)
|
| 201 |
+
|
| 202 |
+
# The machinations below are to ensure that:
|
| 203 |
+
# - Scripts remain in the same order
|
| 204 |
+
# - Scripts are not initialized un-necessarily. If only a
|
| 205 |
+
# script's order in the script list has changed, it is just
|
| 206 |
+
# moved.
|
| 207 |
+
|
| 208 |
+
current = {}
|
| 209 |
+
for a in self.addons:
|
| 210 |
+
current[a.path] = a
|
| 211 |
+
|
| 212 |
+
ordered = []
|
| 213 |
+
newscripts = []
|
| 214 |
+
for s in ctx.options.scripts:
|
| 215 |
+
if s in current:
|
| 216 |
+
ordered.append(current[s])
|
| 217 |
+
else:
|
| 218 |
+
sc = Script(s, True)
|
| 219 |
+
ordered.append(sc)
|
| 220 |
+
newscripts.append(sc)
|
| 221 |
+
|
| 222 |
+
self.addons = ordered
|
| 223 |
+
|
| 224 |
+
for s in newscripts:
|
| 225 |
+
ctx.master.addons.register(s)
|
| 226 |
+
if self.is_running:
|
| 227 |
+
# If we're already running, we configure and tell the addon
|
| 228 |
+
# we're up and running.
|
| 229 |
+
ctx.master.addons.invoke_addon_sync(s, hooks.RunningHook())
|
python/user_packages/Python313/site-packages/mitmproxy/addons/server_side_events.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
from mitmproxy import http
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ServerSideEvents:
|
| 7 |
+
"""
|
| 8 |
+
Server-Side Events are currently swallowed if there's no streaming,
|
| 9 |
+
see https://github.com/mitmproxy/mitmproxy/issues/4469.
|
| 10 |
+
|
| 11 |
+
Until this bug is fixed, this addon warns the user about this.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def response(self, flow: http.HTTPFlow):
|
| 15 |
+
assert flow.response
|
| 16 |
+
is_sse = flow.response.headers.get("content-type", "").startswith(
|
| 17 |
+
"text/event-stream"
|
| 18 |
+
)
|
| 19 |
+
if is_sse and not flow.response.stream:
|
| 20 |
+
logging.warning(
|
| 21 |
+
"mitmproxy currently does not support server side events. As a workaround, you can enable response "
|
| 22 |
+
"streaming for such flows: https://github.com/mitmproxy/mitmproxy/issues/4469"
|
| 23 |
+
)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/serverplayback.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import logging
|
| 3 |
+
import urllib
|
| 4 |
+
from collections.abc import Hashable
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import mitmproxy.types
|
| 9 |
+
from mitmproxy import command
|
| 10 |
+
from mitmproxy import ctx
|
| 11 |
+
from mitmproxy import exceptions
|
| 12 |
+
from mitmproxy import flow
|
| 13 |
+
from mitmproxy import hooks
|
| 14 |
+
from mitmproxy import http
|
| 15 |
+
from mitmproxy import io
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
HASH_OPTIONS = [
|
| 20 |
+
"server_replay_ignore_content",
|
| 21 |
+
"server_replay_ignore_host",
|
| 22 |
+
"server_replay_ignore_params",
|
| 23 |
+
"server_replay_ignore_payload_params",
|
| 24 |
+
"server_replay_ignore_port",
|
| 25 |
+
"server_replay_use_headers",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ServerPlayback:
|
| 30 |
+
flowmap: dict[Hashable, list[http.HTTPFlow]]
|
| 31 |
+
configured: bool
|
| 32 |
+
|
| 33 |
+
def __init__(self):
|
| 34 |
+
self.flowmap = {}
|
| 35 |
+
self.configured = False
|
| 36 |
+
|
| 37 |
+
def load(self, loader):
|
| 38 |
+
loader.add_option(
|
| 39 |
+
"server_replay_kill_extra",
|
| 40 |
+
bool,
|
| 41 |
+
False,
|
| 42 |
+
"Kill extra requests during replay (for which no replayable response was found)."
|
| 43 |
+
"[Deprecated, prefer to use server_replay_extra='kill']",
|
| 44 |
+
)
|
| 45 |
+
loader.add_option(
|
| 46 |
+
"server_replay_extra",
|
| 47 |
+
str,
|
| 48 |
+
"forward",
|
| 49 |
+
"Behaviour for extra requests during replay for which no replayable response was found. "
|
| 50 |
+
"Setting a numeric string value will return an empty HTTP response with the respective status code.",
|
| 51 |
+
choices=["forward", "kill", "204", "400", "404", "500"],
|
| 52 |
+
)
|
| 53 |
+
loader.add_option(
|
| 54 |
+
"server_replay_reuse",
|
| 55 |
+
bool,
|
| 56 |
+
False,
|
| 57 |
+
"""
|
| 58 |
+
Don't remove flows from server replay state after use. This makes it
|
| 59 |
+
possible to replay same response multiple times.
|
| 60 |
+
""",
|
| 61 |
+
)
|
| 62 |
+
loader.add_option(
|
| 63 |
+
"server_replay_nopop",
|
| 64 |
+
bool,
|
| 65 |
+
False,
|
| 66 |
+
"""
|
| 67 |
+
Deprecated alias for `server_replay_reuse`.
|
| 68 |
+
""",
|
| 69 |
+
)
|
| 70 |
+
loader.add_option(
|
| 71 |
+
"server_replay_refresh",
|
| 72 |
+
bool,
|
| 73 |
+
True,
|
| 74 |
+
"""
|
| 75 |
+
Refresh server replay responses by adjusting date, expires and
|
| 76 |
+
last-modified headers, as well as adjusting cookie expiration.
|
| 77 |
+
""",
|
| 78 |
+
)
|
| 79 |
+
loader.add_option(
|
| 80 |
+
"server_replay_use_headers",
|
| 81 |
+
Sequence[str],
|
| 82 |
+
[],
|
| 83 |
+
"""
|
| 84 |
+
Request headers that need to match while searching for a saved flow
|
| 85 |
+
to replay.
|
| 86 |
+
""",
|
| 87 |
+
)
|
| 88 |
+
loader.add_option(
|
| 89 |
+
"server_replay",
|
| 90 |
+
Sequence[str],
|
| 91 |
+
[],
|
| 92 |
+
"Replay server responses from a saved file.",
|
| 93 |
+
)
|
| 94 |
+
loader.add_option(
|
| 95 |
+
"server_replay_ignore_content",
|
| 96 |
+
bool,
|
| 97 |
+
False,
|
| 98 |
+
"Ignore request content while searching for a saved flow to replay.",
|
| 99 |
+
)
|
| 100 |
+
loader.add_option(
|
| 101 |
+
"server_replay_ignore_params",
|
| 102 |
+
Sequence[str],
|
| 103 |
+
[],
|
| 104 |
+
"""
|
| 105 |
+
Request parameters to be ignored while searching for a saved flow
|
| 106 |
+
to replay.
|
| 107 |
+
""",
|
| 108 |
+
)
|
| 109 |
+
loader.add_option(
|
| 110 |
+
"server_replay_ignore_payload_params",
|
| 111 |
+
Sequence[str],
|
| 112 |
+
[],
|
| 113 |
+
"""
|
| 114 |
+
Request payload parameters (application/x-www-form-urlencoded or
|
| 115 |
+
multipart/form-data) to be ignored while searching for a saved flow
|
| 116 |
+
to replay.
|
| 117 |
+
""",
|
| 118 |
+
)
|
| 119 |
+
loader.add_option(
|
| 120 |
+
"server_replay_ignore_host",
|
| 121 |
+
bool,
|
| 122 |
+
False,
|
| 123 |
+
"""
|
| 124 |
+
Ignore request destination host while searching for a saved flow
|
| 125 |
+
to replay.
|
| 126 |
+
""",
|
| 127 |
+
)
|
| 128 |
+
loader.add_option(
|
| 129 |
+
"server_replay_ignore_port",
|
| 130 |
+
bool,
|
| 131 |
+
False,
|
| 132 |
+
"""
|
| 133 |
+
Ignore request destination port while searching for a saved flow
|
| 134 |
+
to replay.
|
| 135 |
+
""",
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
@command.command("replay.server")
|
| 139 |
+
def load_flows(self, flows: Sequence[flow.Flow]) -> None:
|
| 140 |
+
"""
|
| 141 |
+
Replay server responses from flows.
|
| 142 |
+
"""
|
| 143 |
+
self.flowmap = {}
|
| 144 |
+
self.add_flows(flows)
|
| 145 |
+
|
| 146 |
+
@command.command("replay.server.add")
|
| 147 |
+
def add_flows(self, flows: Sequence[flow.Flow]) -> None:
|
| 148 |
+
"""
|
| 149 |
+
Add responses from flows to server replay list.
|
| 150 |
+
"""
|
| 151 |
+
for f in flows:
|
| 152 |
+
if isinstance(f, http.HTTPFlow):
|
| 153 |
+
lst = self.flowmap.setdefault(self._hash(f), [])
|
| 154 |
+
lst.append(f)
|
| 155 |
+
ctx.master.addons.trigger(hooks.UpdateHook([]))
|
| 156 |
+
|
| 157 |
+
@command.command("replay.server.file")
|
| 158 |
+
def load_file(self, path: mitmproxy.types.Path) -> None:
|
| 159 |
+
try:
|
| 160 |
+
flows = io.read_flows_from_paths([path])
|
| 161 |
+
except exceptions.FlowReadException as e:
|
| 162 |
+
raise exceptions.CommandError(str(e))
|
| 163 |
+
self.load_flows(flows)
|
| 164 |
+
|
| 165 |
+
@command.command("replay.server.stop")
|
| 166 |
+
def clear(self) -> None:
|
| 167 |
+
"""
|
| 168 |
+
Stop server replay.
|
| 169 |
+
"""
|
| 170 |
+
self.flowmap = {}
|
| 171 |
+
ctx.master.addons.trigger(hooks.UpdateHook([]))
|
| 172 |
+
|
| 173 |
+
@command.command("replay.server.count")
|
| 174 |
+
def count(self) -> int:
|
| 175 |
+
return sum(len(i) for i in self.flowmap.values())
|
| 176 |
+
|
| 177 |
+
def _hash(self, flow: http.HTTPFlow) -> Hashable:
|
| 178 |
+
"""
|
| 179 |
+
Calculates a loose hash of the flow request.
|
| 180 |
+
"""
|
| 181 |
+
r = flow.request
|
| 182 |
+
_, _, path, _, query, _ = urllib.parse.urlparse(r.url)
|
| 183 |
+
queriesArray = urllib.parse.parse_qsl(query, keep_blank_values=True)
|
| 184 |
+
|
| 185 |
+
key: list[Any] = [str(r.scheme), str(r.method), str(path)]
|
| 186 |
+
if not ctx.options.server_replay_ignore_content:
|
| 187 |
+
if ctx.options.server_replay_ignore_payload_params and r.multipart_form:
|
| 188 |
+
key.extend(
|
| 189 |
+
(k, v)
|
| 190 |
+
for k, v in r.multipart_form.items(multi=True)
|
| 191 |
+
if k.decode(errors="replace")
|
| 192 |
+
not in ctx.options.server_replay_ignore_payload_params
|
| 193 |
+
)
|
| 194 |
+
elif ctx.options.server_replay_ignore_payload_params and r.urlencoded_form:
|
| 195 |
+
key.extend(
|
| 196 |
+
(k, v)
|
| 197 |
+
for k, v in r.urlencoded_form.items(multi=True)
|
| 198 |
+
if k not in ctx.options.server_replay_ignore_payload_params
|
| 199 |
+
)
|
| 200 |
+
else:
|
| 201 |
+
key.append(str(r.raw_content))
|
| 202 |
+
|
| 203 |
+
if not ctx.options.server_replay_ignore_host:
|
| 204 |
+
key.append(r.pretty_host)
|
| 205 |
+
if not ctx.options.server_replay_ignore_port:
|
| 206 |
+
key.append(r.port)
|
| 207 |
+
|
| 208 |
+
filtered = []
|
| 209 |
+
ignore_params = ctx.options.server_replay_ignore_params or []
|
| 210 |
+
for p in queriesArray:
|
| 211 |
+
if p[0] not in ignore_params:
|
| 212 |
+
filtered.append(p)
|
| 213 |
+
for p in filtered:
|
| 214 |
+
key.append(p[0])
|
| 215 |
+
key.append(p[1])
|
| 216 |
+
|
| 217 |
+
if ctx.options.server_replay_use_headers:
|
| 218 |
+
headers = []
|
| 219 |
+
for i in ctx.options.server_replay_use_headers:
|
| 220 |
+
v = r.headers.get(i)
|
| 221 |
+
headers.append((i, v))
|
| 222 |
+
key.append(headers)
|
| 223 |
+
return hashlib.sha256(repr(key).encode("utf8", "surrogateescape")).digest()
|
| 224 |
+
|
| 225 |
+
def next_flow(self, flow: http.HTTPFlow) -> http.HTTPFlow | None:
|
| 226 |
+
"""
|
| 227 |
+
Returns the next flow object, or None if no matching flow was
|
| 228 |
+
found.
|
| 229 |
+
"""
|
| 230 |
+
hash = self._hash(flow)
|
| 231 |
+
if hash in self.flowmap:
|
| 232 |
+
if ctx.options.server_replay_reuse or ctx.options.server_replay_nopop:
|
| 233 |
+
return next(
|
| 234 |
+
(flow for flow in self.flowmap[hash] if flow.response), None
|
| 235 |
+
)
|
| 236 |
+
else:
|
| 237 |
+
ret = self.flowmap[hash].pop(0)
|
| 238 |
+
while not ret.response:
|
| 239 |
+
if self.flowmap[hash]:
|
| 240 |
+
ret = self.flowmap[hash].pop(0)
|
| 241 |
+
else:
|
| 242 |
+
del self.flowmap[hash]
|
| 243 |
+
return None
|
| 244 |
+
if not self.flowmap[hash]:
|
| 245 |
+
del self.flowmap[hash]
|
| 246 |
+
return ret
|
| 247 |
+
else:
|
| 248 |
+
return None
|
| 249 |
+
|
| 250 |
+
def configure(self, updated):
|
| 251 |
+
if ctx.options.server_replay_kill_extra:
|
| 252 |
+
logger.warning(
|
| 253 |
+
"server_replay_kill_extra has been deprecated, "
|
| 254 |
+
"please update your config to use server_replay_extra='kill'."
|
| 255 |
+
)
|
| 256 |
+
if ctx.options.server_replay_nopop: # pragma: no cover
|
| 257 |
+
logger.error(
|
| 258 |
+
"server_replay_nopop has been renamed to server_replay_reuse, please update your config."
|
| 259 |
+
)
|
| 260 |
+
if not self.configured and ctx.options.server_replay:
|
| 261 |
+
self.configured = True
|
| 262 |
+
try:
|
| 263 |
+
flows = io.read_flows_from_paths(ctx.options.server_replay)
|
| 264 |
+
except exceptions.FlowReadException as e:
|
| 265 |
+
raise exceptions.OptionsError(str(e))
|
| 266 |
+
self.load_flows(flows)
|
| 267 |
+
if any(option in updated for option in HASH_OPTIONS):
|
| 268 |
+
self.recompute_hashes()
|
| 269 |
+
|
| 270 |
+
def recompute_hashes(self) -> None:
|
| 271 |
+
"""
|
| 272 |
+
Rebuild flowmap if the hashing method has changed during execution,
|
| 273 |
+
see https://github.com/mitmproxy/mitmproxy/issues/4506
|
| 274 |
+
"""
|
| 275 |
+
flows = [flow for lst in self.flowmap.values() for flow in lst]
|
| 276 |
+
self.load_flows(flows)
|
| 277 |
+
|
| 278 |
+
def request(self, f: http.HTTPFlow) -> None:
|
| 279 |
+
if self.flowmap:
|
| 280 |
+
rflow = self.next_flow(f)
|
| 281 |
+
if rflow:
|
| 282 |
+
assert rflow.response
|
| 283 |
+
response = rflow.response.copy()
|
| 284 |
+
if ctx.options.server_replay_refresh:
|
| 285 |
+
response.refresh()
|
| 286 |
+
f.response = response
|
| 287 |
+
f.is_replay = "response"
|
| 288 |
+
elif (
|
| 289 |
+
ctx.options.server_replay_kill_extra
|
| 290 |
+
or ctx.options.server_replay_extra == "kill"
|
| 291 |
+
):
|
| 292 |
+
logging.warning(
|
| 293 |
+
"server_playback: killed non-replay request {}".format(
|
| 294 |
+
f.request.url
|
| 295 |
+
)
|
| 296 |
+
)
|
| 297 |
+
f.kill()
|
| 298 |
+
elif ctx.options.server_replay_extra != "forward":
|
| 299 |
+
logging.warning(
|
| 300 |
+
"server_playback: returned {} non-replay request {}".format(
|
| 301 |
+
ctx.options.server_replay_extra, f.request.url
|
| 302 |
+
)
|
| 303 |
+
)
|
| 304 |
+
f.response = http.Response.make(int(ctx.options.server_replay_extra))
|
| 305 |
+
f.is_replay = "response"
|
python/user_packages/Python313/site-packages/mitmproxy/addons/stickyauth.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
from mitmproxy import ctx
|
| 4 |
+
from mitmproxy import exceptions
|
| 5 |
+
from mitmproxy import flowfilter
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class StickyAuth:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self.flt = None
|
| 11 |
+
self.hosts = {}
|
| 12 |
+
|
| 13 |
+
def load(self, loader):
|
| 14 |
+
loader.add_option(
|
| 15 |
+
"stickyauth",
|
| 16 |
+
Optional[str],
|
| 17 |
+
None,
|
| 18 |
+
"Set sticky auth filter. Matched against requests.",
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
def configure(self, updated):
|
| 22 |
+
if "stickyauth" in updated:
|
| 23 |
+
if ctx.options.stickyauth:
|
| 24 |
+
try:
|
| 25 |
+
self.flt = flowfilter.parse(ctx.options.stickyauth)
|
| 26 |
+
except ValueError as e:
|
| 27 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 28 |
+
else:
|
| 29 |
+
self.flt = None
|
| 30 |
+
|
| 31 |
+
def request(self, flow):
|
| 32 |
+
if self.flt:
|
| 33 |
+
host = flow.request.host
|
| 34 |
+
if "authorization" in flow.request.headers:
|
| 35 |
+
self.hosts[host] = flow.request.headers["authorization"]
|
| 36 |
+
elif flowfilter.match(self.flt, flow):
|
| 37 |
+
if host in self.hosts:
|
| 38 |
+
flow.request.headers["authorization"] = self.hosts[host]
|
python/user_packages/Python313/site-packages/mitmproxy/addons/stickycookie.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
from http import cookiejar
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from mitmproxy import ctx
|
| 6 |
+
from mitmproxy import exceptions
|
| 7 |
+
from mitmproxy import flowfilter
|
| 8 |
+
from mitmproxy import http
|
| 9 |
+
from mitmproxy.net.http import cookies
|
| 10 |
+
|
| 11 |
+
TOrigin = tuple[str, int, str]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def ckey(attrs: dict[str, str], f: http.HTTPFlow) -> TOrigin:
|
| 15 |
+
"""
|
| 16 |
+
Returns a (domain, port, path) tuple.
|
| 17 |
+
"""
|
| 18 |
+
domain = f.request.host
|
| 19 |
+
path = "/"
|
| 20 |
+
if "domain" in attrs:
|
| 21 |
+
domain = attrs["domain"]
|
| 22 |
+
if "path" in attrs:
|
| 23 |
+
path = attrs["path"]
|
| 24 |
+
return (domain, f.request.port, path)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def domain_match(a: str, b: str) -> bool:
|
| 28 |
+
if cookiejar.domain_match(a, b): # type: ignore
|
| 29 |
+
return True
|
| 30 |
+
elif cookiejar.domain_match(a, b.strip(".")): # type: ignore
|
| 31 |
+
return True
|
| 32 |
+
return False
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class StickyCookie:
|
| 36 |
+
def __init__(self) -> None:
|
| 37 |
+
self.jar: collections.defaultdict[TOrigin, dict[str, str]] = (
|
| 38 |
+
collections.defaultdict(dict)
|
| 39 |
+
)
|
| 40 |
+
self.flt: flowfilter.TFilter | None = None
|
| 41 |
+
|
| 42 |
+
def load(self, loader):
|
| 43 |
+
loader.add_option(
|
| 44 |
+
"stickycookie",
|
| 45 |
+
Optional[str],
|
| 46 |
+
None,
|
| 47 |
+
"Set sticky cookie filter. Matched against requests.",
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def configure(self, updated):
|
| 51 |
+
if "stickycookie" in updated:
|
| 52 |
+
if ctx.options.stickycookie:
|
| 53 |
+
try:
|
| 54 |
+
self.flt = flowfilter.parse(ctx.options.stickycookie)
|
| 55 |
+
except ValueError as e:
|
| 56 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 57 |
+
else:
|
| 58 |
+
self.flt = None
|
| 59 |
+
|
| 60 |
+
def response(self, flow: http.HTTPFlow):
|
| 61 |
+
assert flow.response
|
| 62 |
+
if self.flt:
|
| 63 |
+
for name, (value, attrs) in flow.response.cookies.items(multi=True):
|
| 64 |
+
# FIXME: We now know that Cookie.py screws up some cookies with
|
| 65 |
+
# valid RFC 822/1123 datetime specifications for expiry. Sigh.
|
| 66 |
+
dom_port_path = ckey(attrs, flow)
|
| 67 |
+
|
| 68 |
+
if domain_match(flow.request.host, dom_port_path[0]):
|
| 69 |
+
if cookies.is_expired(attrs):
|
| 70 |
+
# Remove the cookie from jar
|
| 71 |
+
self.jar[dom_port_path].pop(name, None)
|
| 72 |
+
|
| 73 |
+
# If all cookies of a dom_port_path have been removed
|
| 74 |
+
# then remove it from the jar itself
|
| 75 |
+
if not self.jar[dom_port_path]:
|
| 76 |
+
self.jar.pop(dom_port_path, None)
|
| 77 |
+
else:
|
| 78 |
+
self.jar[dom_port_path][name] = value
|
| 79 |
+
|
| 80 |
+
def request(self, flow: http.HTTPFlow):
|
| 81 |
+
if self.flt:
|
| 82 |
+
cookie_list: list[tuple[str, str]] = []
|
| 83 |
+
if flowfilter.match(self.flt, flow):
|
| 84 |
+
for (domain, port, path), c in self.jar.items():
|
| 85 |
+
match = [
|
| 86 |
+
domain_match(flow.request.host, domain),
|
| 87 |
+
flow.request.port == port,
|
| 88 |
+
flow.request.path.startswith(path),
|
| 89 |
+
]
|
| 90 |
+
if all(match):
|
| 91 |
+
cookie_list.extend(c.items())
|
| 92 |
+
if cookie_list:
|
| 93 |
+
# FIXME: we need to formalise this...
|
| 94 |
+
flow.metadata["stickycookie"] = True
|
| 95 |
+
flow.request.headers["cookie"] = cookies.format_cookie_header(
|
| 96 |
+
cookie_list
|
| 97 |
+
)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/strip_dns_https_records.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mitmproxy import ctx
|
| 2 |
+
from mitmproxy import dns
|
| 3 |
+
from mitmproxy.net.dns import types
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class StripDnsHttpsRecords:
|
| 7 |
+
def load(self, loader):
|
| 8 |
+
loader.add_option(
|
| 9 |
+
"strip_ech",
|
| 10 |
+
bool,
|
| 11 |
+
True,
|
| 12 |
+
"Strip Encrypted ClientHello (ECH) data from DNS HTTPS records so that mitmproxy can generate matching certificates.",
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
def dns_response(self, flow: dns.DNSFlow):
|
| 16 |
+
assert flow.response
|
| 17 |
+
if ctx.options.strip_ech:
|
| 18 |
+
for answer in flow.response.answers:
|
| 19 |
+
if answer.type == types.HTTPS:
|
| 20 |
+
answer.https_ech = None
|
| 21 |
+
if not ctx.options.http3:
|
| 22 |
+
for answer in flow.response.answers:
|
| 23 |
+
if (
|
| 24 |
+
answer.type == types.HTTPS
|
| 25 |
+
and answer.https_alpn is not None
|
| 26 |
+
and any(
|
| 27 |
+
# HTTP/3 or any of the spec drafts (h3-...)?
|
| 28 |
+
a == b"h3" or a.startswith(b"h3-")
|
| 29 |
+
for a in answer.https_alpn
|
| 30 |
+
)
|
| 31 |
+
):
|
| 32 |
+
alpns = tuple(
|
| 33 |
+
a
|
| 34 |
+
for a in answer.https_alpn
|
| 35 |
+
if a != b"h3" and not a.startswith(b"h3-")
|
| 36 |
+
)
|
| 37 |
+
answer.https_alpn = alpns or None
|
python/user_packages/Python313/site-packages/mitmproxy/addons/termlog.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import logging
|
| 5 |
+
import sys
|
| 6 |
+
from typing import IO
|
| 7 |
+
|
| 8 |
+
from mitmproxy import ctx
|
| 9 |
+
from mitmproxy import log
|
| 10 |
+
from mitmproxy.utils import vt_codes
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TermLog:
|
| 14 |
+
_teardown_task: asyncio.Task | None = None
|
| 15 |
+
|
| 16 |
+
def __init__(self, out: IO[str] | None = None):
|
| 17 |
+
self.logger = TermLogHandler(out)
|
| 18 |
+
self.logger.install()
|
| 19 |
+
|
| 20 |
+
def load(self, loader):
|
| 21 |
+
loader.add_option(
|
| 22 |
+
"termlog_verbosity", str, "info", "Log verbosity.", choices=log.LogLevels
|
| 23 |
+
)
|
| 24 |
+
self.logger.setLevel(logging.INFO)
|
| 25 |
+
|
| 26 |
+
def configure(self, updated):
|
| 27 |
+
if "termlog_verbosity" in updated:
|
| 28 |
+
self.logger.setLevel(ctx.options.termlog_verbosity.upper())
|
| 29 |
+
|
| 30 |
+
def uninstall(self) -> None:
|
| 31 |
+
# uninstall the log dumper.
|
| 32 |
+
# This happens at the very very end after done() is completed,
|
| 33 |
+
# because we don't want to uninstall while other addons are still logging.
|
| 34 |
+
self.logger.uninstall()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TermLogHandler(log.MitmLogHandler):
|
| 38 |
+
def __init__(self, out: IO[str] | None = None):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.file: IO[str] = out or sys.stdout
|
| 41 |
+
self.has_vt_codes = vt_codes.ensure_supported(self.file)
|
| 42 |
+
self.formatter = log.MitmFormatter(self.has_vt_codes)
|
| 43 |
+
|
| 44 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 45 |
+
try:
|
| 46 |
+
print(self.format(record), file=self.file)
|
| 47 |
+
except OSError:
|
| 48 |
+
# We cannot print, exit immediately.
|
| 49 |
+
# See https://github.com/mitmproxy/mitmproxy/issues/4669
|
| 50 |
+
sys.exit(1)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/tlsconfig.py
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ipaddress
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import ssl
|
| 5 |
+
import urllib.parse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
from typing import Literal
|
| 9 |
+
from typing import TypedDict
|
| 10 |
+
|
| 11 |
+
from aioquic.h3.connection import H3_ALPN
|
| 12 |
+
from aioquic.tls import CipherSuite
|
| 13 |
+
from cryptography import x509
|
| 14 |
+
from OpenSSL import SSL
|
| 15 |
+
|
| 16 |
+
from mitmproxy import certs
|
| 17 |
+
from mitmproxy import connection
|
| 18 |
+
from mitmproxy import ctx
|
| 19 |
+
from mitmproxy import exceptions
|
| 20 |
+
from mitmproxy import http
|
| 21 |
+
from mitmproxy import tls
|
| 22 |
+
from mitmproxy.net import tls as net_tls
|
| 23 |
+
from mitmproxy.options import CONF_BASENAME
|
| 24 |
+
from mitmproxy.proxy import context
|
| 25 |
+
from mitmproxy.proxy.layers import modes
|
| 26 |
+
from mitmproxy.proxy.layers import quic
|
| 27 |
+
from mitmproxy.proxy.layers import tls as proxy_tls
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
# We manually need to specify this, otherwise OpenSSL may select a non-HTTP2 cipher by default.
|
| 32 |
+
# https://ssl-config.mozilla.org/#config=old
|
| 33 |
+
|
| 34 |
+
_DEFAULT_CIPHERS = (
|
| 35 |
+
"ECDHE-ECDSA-AES128-GCM-SHA256",
|
| 36 |
+
"ECDHE-RSA-AES128-GCM-SHA256",
|
| 37 |
+
"ECDHE-ECDSA-AES256-GCM-SHA384",
|
| 38 |
+
"ECDHE-RSA-AES256-GCM-SHA384",
|
| 39 |
+
"ECDHE-ECDSA-CHACHA20-POLY1305",
|
| 40 |
+
"ECDHE-RSA-CHACHA20-POLY1305",
|
| 41 |
+
"DHE-RSA-AES128-GCM-SHA256",
|
| 42 |
+
"DHE-RSA-AES256-GCM-SHA384",
|
| 43 |
+
"DHE-RSA-CHACHA20-POLY1305",
|
| 44 |
+
"ECDHE-ECDSA-AES128-SHA256",
|
| 45 |
+
"ECDHE-RSA-AES128-SHA256",
|
| 46 |
+
"ECDHE-ECDSA-AES128-SHA",
|
| 47 |
+
"ECDHE-RSA-AES128-SHA",
|
| 48 |
+
"ECDHE-ECDSA-AES256-SHA384",
|
| 49 |
+
"ECDHE-RSA-AES256-SHA384",
|
| 50 |
+
"ECDHE-ECDSA-AES256-SHA",
|
| 51 |
+
"ECDHE-RSA-AES256-SHA",
|
| 52 |
+
"DHE-RSA-AES128-SHA256",
|
| 53 |
+
"DHE-RSA-AES256-SHA256",
|
| 54 |
+
"AES128-GCM-SHA256",
|
| 55 |
+
"AES256-GCM-SHA384",
|
| 56 |
+
"AES128-SHA256",
|
| 57 |
+
"AES256-SHA256",
|
| 58 |
+
"AES128-SHA",
|
| 59 |
+
"AES256-SHA",
|
| 60 |
+
"DES-CBC3-SHA",
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
_DEFAULT_CIPHERS_WITH_SECLEVEL_0 = ("@SECLEVEL=0", *_DEFAULT_CIPHERS)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _default_ciphers(
|
| 67 |
+
min_tls_version: net_tls.Version,
|
| 68 |
+
) -> tuple[str, ...]:
|
| 69 |
+
"""
|
| 70 |
+
@SECLEVEL=0 is necessary for TLS 1.1 and below to work,
|
| 71 |
+
see https://github.com/pyca/cryptography/issues/9523
|
| 72 |
+
"""
|
| 73 |
+
if min_tls_version in net_tls.INSECURE_TLS_MIN_VERSIONS:
|
| 74 |
+
return _DEFAULT_CIPHERS_WITH_SECLEVEL_0
|
| 75 |
+
else:
|
| 76 |
+
return _DEFAULT_CIPHERS
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# 2022/05: X509_CHECK_FLAG_NEVER_CHECK_SUBJECT is not available in LibreSSL, ignore gracefully as it's not critical.
|
| 80 |
+
DEFAULT_HOSTFLAGS = (
|
| 81 |
+
SSL._lib.X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS # type: ignore
|
| 82 |
+
| getattr(SSL._lib, "X509_CHECK_FLAG_NEVER_CHECK_SUBJECT", 0) # type: ignore
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class AppData(TypedDict):
|
| 87 |
+
client_alpn: bytes | None
|
| 88 |
+
server_alpn: bytes | None
|
| 89 |
+
http2: bool
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def alpn_select_callback(conn: SSL.Connection, options: list[bytes]) -> Any:
|
| 93 |
+
app_data: AppData = conn.get_app_data()
|
| 94 |
+
client_alpn = app_data["client_alpn"]
|
| 95 |
+
server_alpn = app_data["server_alpn"]
|
| 96 |
+
http2 = app_data["http2"]
|
| 97 |
+
if client_alpn is not None:
|
| 98 |
+
if client_alpn in options:
|
| 99 |
+
return client_alpn
|
| 100 |
+
else:
|
| 101 |
+
return SSL.NO_OVERLAPPING_PROTOCOLS
|
| 102 |
+
if server_alpn and server_alpn in options:
|
| 103 |
+
return server_alpn
|
| 104 |
+
if server_alpn == b"":
|
| 105 |
+
# We do have a server connection, but the remote server refused to negotiate a protocol:
|
| 106 |
+
# We need to mirror this on the client connection.
|
| 107 |
+
return SSL.NO_OVERLAPPING_PROTOCOLS
|
| 108 |
+
http_alpns = proxy_tls.HTTP_ALPNS if http2 else proxy_tls.HTTP1_ALPNS
|
| 109 |
+
# client sends in order of preference, so we are nice and respect that.
|
| 110 |
+
for alpn in options:
|
| 111 |
+
if alpn in http_alpns:
|
| 112 |
+
return alpn
|
| 113 |
+
else:
|
| 114 |
+
return SSL.NO_OVERLAPPING_PROTOCOLS
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TlsConfig:
|
| 118 |
+
"""
|
| 119 |
+
This addon supplies the proxy core with the desired OpenSSL connection objects to negotiate TLS.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
certstore: certs.CertStore = None # type: ignore
|
| 123 |
+
|
| 124 |
+
# TODO: We should support configuring TLS 1.3 cipher suites (https://github.com/mitmproxy/mitmproxy/issues/4260)
|
| 125 |
+
# TODO: We should re-use SSL.Context options here, if only for TLS session resumption.
|
| 126 |
+
# This may require patches to pyOpenSSL, as some functionality is only exposed on contexts.
|
| 127 |
+
# TODO: This addon should manage the following options itself, which are current defined in mitmproxy/options.py:
|
| 128 |
+
# - upstream_cert
|
| 129 |
+
# - add_upstream_certs_to_client_chain
|
| 130 |
+
# - key_size
|
| 131 |
+
# - certs
|
| 132 |
+
# - cert_passphrase
|
| 133 |
+
# - ssl_verify_upstream_trusted_ca
|
| 134 |
+
# - ssl_verify_upstream_trusted_confdir
|
| 135 |
+
|
| 136 |
+
def load(self, loader):
|
| 137 |
+
insecure_tls_min_versions = (
|
| 138 |
+
", ".join(x.name for x in net_tls.INSECURE_TLS_MIN_VERSIONS[:-1])
|
| 139 |
+
+ f" and {net_tls.INSECURE_TLS_MIN_VERSIONS[-1].name}"
|
| 140 |
+
)
|
| 141 |
+
loader.add_option(
|
| 142 |
+
name="tls_version_client_min",
|
| 143 |
+
typespec=str,
|
| 144 |
+
default=net_tls.DEFAULT_MIN_VERSION.name,
|
| 145 |
+
choices=[x.name for x in net_tls.Version],
|
| 146 |
+
help=f"Set the minimum TLS version for client connections. "
|
| 147 |
+
f"{insecure_tls_min_versions} are insecure.",
|
| 148 |
+
)
|
| 149 |
+
loader.add_option(
|
| 150 |
+
name="tls_version_client_max",
|
| 151 |
+
typespec=str,
|
| 152 |
+
default=net_tls.DEFAULT_MAX_VERSION.name,
|
| 153 |
+
choices=[x.name for x in net_tls.Version],
|
| 154 |
+
help=f"Set the maximum TLS version for client connections.",
|
| 155 |
+
)
|
| 156 |
+
loader.add_option(
|
| 157 |
+
name="tls_version_server_min",
|
| 158 |
+
typespec=str,
|
| 159 |
+
default=net_tls.DEFAULT_MIN_VERSION.name,
|
| 160 |
+
choices=[x.name for x in net_tls.Version],
|
| 161 |
+
help=f"Set the minimum TLS version for server connections. "
|
| 162 |
+
f"{insecure_tls_min_versions} are insecure.",
|
| 163 |
+
)
|
| 164 |
+
loader.add_option(
|
| 165 |
+
name="tls_version_server_max",
|
| 166 |
+
typespec=str,
|
| 167 |
+
default=net_tls.DEFAULT_MAX_VERSION.name,
|
| 168 |
+
choices=[x.name for x in net_tls.Version],
|
| 169 |
+
help=f"Set the maximum TLS version for server connections.",
|
| 170 |
+
)
|
| 171 |
+
loader.add_option(
|
| 172 |
+
name="tls_ecdh_curve_client",
|
| 173 |
+
typespec=str | None,
|
| 174 |
+
default=None,
|
| 175 |
+
help="Use a specific elliptic curve for ECDHE key exchange on client connections. "
|
| 176 |
+
'OpenSSL syntax, for example "prime256v1" (see `openssl ecparam -list_curves`).',
|
| 177 |
+
)
|
| 178 |
+
loader.add_option(
|
| 179 |
+
name="tls_ecdh_curve_server",
|
| 180 |
+
typespec=str | None,
|
| 181 |
+
default=None,
|
| 182 |
+
help="Use a specific elliptic curve for ECDHE key exchange on server connections. "
|
| 183 |
+
'OpenSSL syntax, for example "prime256v1" (see `openssl ecparam -list_curves`).',
|
| 184 |
+
)
|
| 185 |
+
loader.add_option(
|
| 186 |
+
name="request_client_cert",
|
| 187 |
+
typespec=bool,
|
| 188 |
+
default=False,
|
| 189 |
+
help=f"Requests a client certificate (TLS message 'CertificateRequest') to establish a mutual TLS connection between client and mitmproxy (combined with 'client_certs' option for mitmproxy and upstream).",
|
| 190 |
+
)
|
| 191 |
+
loader.add_option(
|
| 192 |
+
"ciphers_client",
|
| 193 |
+
str | None,
|
| 194 |
+
None,
|
| 195 |
+
"Set supported ciphers for client <-> mitmproxy connections using OpenSSL syntax.",
|
| 196 |
+
)
|
| 197 |
+
loader.add_option(
|
| 198 |
+
"ciphers_server",
|
| 199 |
+
str | None,
|
| 200 |
+
None,
|
| 201 |
+
"Set supported ciphers for mitmproxy <-> server connections using OpenSSL syntax.",
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
def tls_clienthello(self, tls_clienthello: tls.ClientHelloData):
|
| 205 |
+
conn_context = tls_clienthello.context
|
| 206 |
+
tls_clienthello.establish_server_tls_first = (
|
| 207 |
+
conn_context.server.tls and ctx.options.connection_strategy == "eager"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def tls_start_client(self, tls_start: tls.TlsData) -> None:
|
| 211 |
+
"""Establish TLS or DTLS between client and proxy."""
|
| 212 |
+
if tls_start.ssl_conn is not None:
|
| 213 |
+
return # a user addon has already provided the pyOpenSSL context.
|
| 214 |
+
|
| 215 |
+
assert isinstance(tls_start.conn, connection.Client)
|
| 216 |
+
|
| 217 |
+
client: connection.Client = tls_start.conn
|
| 218 |
+
server: connection.Server = tls_start.context.server
|
| 219 |
+
|
| 220 |
+
entry = self.get_cert(tls_start.context)
|
| 221 |
+
|
| 222 |
+
if not client.cipher_list and ctx.options.ciphers_client:
|
| 223 |
+
client.cipher_list = ctx.options.ciphers_client.split(":")
|
| 224 |
+
# don't assign to client.cipher_list, doesn't need to be stored.
|
| 225 |
+
cipher_list = client.cipher_list or _default_ciphers(
|
| 226 |
+
net_tls.Version[ctx.options.tls_version_client_min]
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
if ctx.options.add_upstream_certs_to_client_chain: # pragma: no cover
|
| 230 |
+
# exempted from coverage until https://bugs.python.org/issue18233 is fixed.
|
| 231 |
+
extra_chain_certs = server.certificate_list
|
| 232 |
+
else:
|
| 233 |
+
extra_chain_certs = []
|
| 234 |
+
|
| 235 |
+
ssl_ctx = net_tls.create_client_proxy_context(
|
| 236 |
+
method=net_tls.Method.DTLS_SERVER_METHOD
|
| 237 |
+
if tls_start.is_dtls
|
| 238 |
+
else net_tls.Method.TLS_SERVER_METHOD,
|
| 239 |
+
min_version=net_tls.Version[ctx.options.tls_version_client_min],
|
| 240 |
+
max_version=net_tls.Version[ctx.options.tls_version_client_max],
|
| 241 |
+
cipher_list=tuple(cipher_list),
|
| 242 |
+
ecdh_curve=net_tls.get_curve(ctx.options.tls_ecdh_curve_client),
|
| 243 |
+
chain_file=entry.chain_file,
|
| 244 |
+
request_client_cert=ctx.options.request_client_cert,
|
| 245 |
+
alpn_select_callback=alpn_select_callback,
|
| 246 |
+
extra_chain_certs=tuple(extra_chain_certs),
|
| 247 |
+
dhparams=self.certstore.dhparams,
|
| 248 |
+
)
|
| 249 |
+
tls_start.ssl_conn = SSL.Connection(ssl_ctx)
|
| 250 |
+
|
| 251 |
+
tls_start.ssl_conn.use_certificate(entry.cert.to_cryptography())
|
| 252 |
+
tls_start.ssl_conn.use_privatekey(entry.privatekey)
|
| 253 |
+
|
| 254 |
+
# Force HTTP/1 for secure web proxies, we currently don't support CONNECT over HTTP/2.
|
| 255 |
+
# There is a proof-of-concept branch at https://github.com/mhils/mitmproxy/tree/http2-proxy,
|
| 256 |
+
# but the complexity outweighs the benefits for now.
|
| 257 |
+
if len(tls_start.context.layers) == 2 and isinstance(
|
| 258 |
+
tls_start.context.layers[0], modes.HttpProxy
|
| 259 |
+
):
|
| 260 |
+
client_alpn: bytes | None = b"http/1.1"
|
| 261 |
+
else:
|
| 262 |
+
client_alpn = client.alpn
|
| 263 |
+
|
| 264 |
+
tls_start.ssl_conn.set_app_data(
|
| 265 |
+
AppData(
|
| 266 |
+
client_alpn=client_alpn,
|
| 267 |
+
server_alpn=server.alpn,
|
| 268 |
+
http2=ctx.options.http2,
|
| 269 |
+
)
|
| 270 |
+
)
|
| 271 |
+
tls_start.ssl_conn.set_accept_state()
|
| 272 |
+
|
| 273 |
+
def tls_start_server(self, tls_start: tls.TlsData) -> None:
|
| 274 |
+
"""Establish TLS or DTLS between proxy and server."""
|
| 275 |
+
if tls_start.ssl_conn is not None:
|
| 276 |
+
return # a user addon has already provided the pyOpenSSL context.
|
| 277 |
+
|
| 278 |
+
assert isinstance(tls_start.conn, connection.Server)
|
| 279 |
+
|
| 280 |
+
client: connection.Client = tls_start.context.client
|
| 281 |
+
# tls_start.conn may be different from tls_start.context.server, e.g. an upstream HTTPS proxy.
|
| 282 |
+
server: connection.Server = tls_start.conn
|
| 283 |
+
assert server.address
|
| 284 |
+
|
| 285 |
+
if ctx.options.ssl_insecure:
|
| 286 |
+
verify = net_tls.Verify.VERIFY_NONE
|
| 287 |
+
else:
|
| 288 |
+
verify = net_tls.Verify.VERIFY_PEER
|
| 289 |
+
|
| 290 |
+
if server.sni is None:
|
| 291 |
+
server.sni = client.sni or server.address[0]
|
| 292 |
+
|
| 293 |
+
if not server.alpn_offers:
|
| 294 |
+
if client.alpn_offers:
|
| 295 |
+
if ctx.options.http2:
|
| 296 |
+
# We would perfectly support HTTP/1 -> HTTP/2, but we want to keep things on the same protocol
|
| 297 |
+
# version. There are some edge cases where we want to mirror the regular server's behavior
|
| 298 |
+
# accurately, for example header capitalization.
|
| 299 |
+
server.alpn_offers = tuple(client.alpn_offers)
|
| 300 |
+
else:
|
| 301 |
+
server.alpn_offers = tuple(
|
| 302 |
+
x for x in client.alpn_offers if x != b"h2"
|
| 303 |
+
)
|
| 304 |
+
else:
|
| 305 |
+
# We either have no client TLS or a client without ALPN.
|
| 306 |
+
# - If the client does use TLS but did not send an ALPN extension, we want to mirror that upstream.
|
| 307 |
+
# - If the client does not use TLS, there's no clear-cut answer. As a pragmatic approach, we also do
|
| 308 |
+
# not send any ALPN extension in this case, which defaults to whatever protocol we are speaking
|
| 309 |
+
# or falls back to HTTP.
|
| 310 |
+
server.alpn_offers = []
|
| 311 |
+
|
| 312 |
+
if not server.cipher_list and ctx.options.ciphers_server:
|
| 313 |
+
server.cipher_list = ctx.options.ciphers_server.split(":")
|
| 314 |
+
# don't assign to client.cipher_list, doesn't need to be stored.
|
| 315 |
+
cipher_list = server.cipher_list or _default_ciphers(
|
| 316 |
+
net_tls.Version[ctx.options.tls_version_server_min]
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
client_cert: str | None = None
|
| 320 |
+
if ctx.options.client_certs:
|
| 321 |
+
client_certs = os.path.expanduser(ctx.options.client_certs)
|
| 322 |
+
if os.path.isfile(client_certs):
|
| 323 |
+
client_cert = client_certs
|
| 324 |
+
else:
|
| 325 |
+
server_name: str = server.sni or server.address[0]
|
| 326 |
+
p = os.path.join(client_certs, f"{server_name}.pem")
|
| 327 |
+
if os.path.isfile(p):
|
| 328 |
+
client_cert = p
|
| 329 |
+
|
| 330 |
+
ssl_ctx = net_tls.create_proxy_server_context(
|
| 331 |
+
method=net_tls.Method.DTLS_CLIENT_METHOD
|
| 332 |
+
if tls_start.is_dtls
|
| 333 |
+
else net_tls.Method.TLS_CLIENT_METHOD,
|
| 334 |
+
min_version=net_tls.Version[ctx.options.tls_version_server_min],
|
| 335 |
+
max_version=net_tls.Version[ctx.options.tls_version_server_max],
|
| 336 |
+
cipher_list=tuple(cipher_list),
|
| 337 |
+
ecdh_curve=net_tls.get_curve(ctx.options.tls_ecdh_curve_server),
|
| 338 |
+
verify=verify,
|
| 339 |
+
ca_path=ctx.options.ssl_verify_upstream_trusted_confdir,
|
| 340 |
+
ca_pemfile=ctx.options.ssl_verify_upstream_trusted_ca,
|
| 341 |
+
client_cert=client_cert,
|
| 342 |
+
legacy_server_connect=ctx.options.ssl_insecure,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
tls_start.ssl_conn = SSL.Connection(ssl_ctx)
|
| 346 |
+
if server.sni:
|
| 347 |
+
# We need to set SNI + enable hostname verification.
|
| 348 |
+
assert isinstance(server.sni, str)
|
| 349 |
+
# Manually enable hostname verification on the context object.
|
| 350 |
+
# https://wiki.openssl.org/index.php/Hostname_validation
|
| 351 |
+
param = SSL._lib.SSL_get0_param(tls_start.ssl_conn._ssl) # type: ignore
|
| 352 |
+
# Matching on the CN is disabled in both Chrome and Firefox, so we disable it, too.
|
| 353 |
+
# https://www.chromestatus.com/feature/4981025180483584
|
| 354 |
+
|
| 355 |
+
SSL._lib.X509_VERIFY_PARAM_set_hostflags(param, DEFAULT_HOSTFLAGS) # type: ignore
|
| 356 |
+
|
| 357 |
+
try:
|
| 358 |
+
ip: bytes = ipaddress.ip_address(server.sni).packed
|
| 359 |
+
except ValueError:
|
| 360 |
+
host_name = server.sni.encode("idna")
|
| 361 |
+
tls_start.ssl_conn.set_tlsext_host_name(host_name)
|
| 362 |
+
ok = SSL._lib.X509_VERIFY_PARAM_set1_host( # type: ignore
|
| 363 |
+
param, host_name, len(host_name)
|
| 364 |
+
) # type: ignore
|
| 365 |
+
SSL._openssl_assert(ok == 1) # type: ignore
|
| 366 |
+
else:
|
| 367 |
+
# RFC 6066: Literal IPv4 and IPv6 addresses are not permitted in "HostName",
|
| 368 |
+
# so we don't call set_tlsext_host_name.
|
| 369 |
+
ok = SSL._lib.X509_VERIFY_PARAM_set1_ip(param, ip, len(ip)) # type: ignore
|
| 370 |
+
SSL._openssl_assert(ok == 1) # type: ignore
|
| 371 |
+
elif verify is not net_tls.Verify.VERIFY_NONE:
|
| 372 |
+
raise ValueError("Cannot validate certificate hostname without SNI")
|
| 373 |
+
|
| 374 |
+
if server.alpn_offers:
|
| 375 |
+
tls_start.ssl_conn.set_alpn_protos(list(server.alpn_offers))
|
| 376 |
+
|
| 377 |
+
tls_start.ssl_conn.set_connect_state()
|
| 378 |
+
|
| 379 |
+
def quic_start_client(self, tls_start: quic.QuicTlsData) -> None:
|
| 380 |
+
"""Establish QUIC between client and proxy."""
|
| 381 |
+
if tls_start.settings is not None:
|
| 382 |
+
return # a user addon has already provided the settings.
|
| 383 |
+
tls_start.settings = quic.QuicTlsSettings()
|
| 384 |
+
|
| 385 |
+
# keep the following part in sync with `tls_start_client`
|
| 386 |
+
assert isinstance(tls_start.conn, connection.Client)
|
| 387 |
+
|
| 388 |
+
client: connection.Client = tls_start.conn
|
| 389 |
+
server: connection.Server = tls_start.context.server
|
| 390 |
+
|
| 391 |
+
entry = self.get_cert(tls_start.context)
|
| 392 |
+
|
| 393 |
+
if not client.cipher_list and ctx.options.ciphers_client:
|
| 394 |
+
client.cipher_list = ctx.options.ciphers_client.split(":")
|
| 395 |
+
|
| 396 |
+
if ctx.options.add_upstream_certs_to_client_chain: # pragma: no cover
|
| 397 |
+
extra_chain_certs = server.certificate_list
|
| 398 |
+
else:
|
| 399 |
+
extra_chain_certs = []
|
| 400 |
+
|
| 401 |
+
# set context parameters
|
| 402 |
+
if client.cipher_list:
|
| 403 |
+
tls_start.settings.cipher_suites = [
|
| 404 |
+
CipherSuite[cipher] for cipher in client.cipher_list
|
| 405 |
+
]
|
| 406 |
+
# if we don't have upstream ALPN, we allow all offered by the client
|
| 407 |
+
tls_start.settings.alpn_protocols = [
|
| 408 |
+
alpn.decode("ascii")
|
| 409 |
+
for alpn in [alpn for alpn in (client.alpn, server.alpn) if alpn]
|
| 410 |
+
or client.alpn_offers
|
| 411 |
+
]
|
| 412 |
+
|
| 413 |
+
# set the certificates
|
| 414 |
+
tls_start.settings.certificate = entry.cert._cert
|
| 415 |
+
tls_start.settings.certificate_private_key = entry.privatekey
|
| 416 |
+
tls_start.settings.certificate_chain = [
|
| 417 |
+
cert._cert for cert in (*entry.chain_certs, *extra_chain_certs)
|
| 418 |
+
]
|
| 419 |
+
|
| 420 |
+
def quic_start_server(self, tls_start: quic.QuicTlsData) -> None:
|
| 421 |
+
"""Establish QUIC between proxy and server."""
|
| 422 |
+
if tls_start.settings is not None:
|
| 423 |
+
return # a user addon has already provided the settings.
|
| 424 |
+
tls_start.settings = quic.QuicTlsSettings()
|
| 425 |
+
|
| 426 |
+
# keep the following part in sync with `tls_start_server`
|
| 427 |
+
assert isinstance(tls_start.conn, connection.Server)
|
| 428 |
+
|
| 429 |
+
client: connection.Client = tls_start.context.client
|
| 430 |
+
server: connection.Server = tls_start.conn
|
| 431 |
+
assert server.address
|
| 432 |
+
|
| 433 |
+
if ctx.options.ssl_insecure:
|
| 434 |
+
tls_start.settings.verify_mode = ssl.CERT_NONE
|
| 435 |
+
else:
|
| 436 |
+
tls_start.settings.verify_mode = ssl.CERT_REQUIRED
|
| 437 |
+
|
| 438 |
+
if server.sni is None:
|
| 439 |
+
server.sni = client.sni or server.address[0]
|
| 440 |
+
|
| 441 |
+
if not server.alpn_offers:
|
| 442 |
+
if client.alpn_offers:
|
| 443 |
+
server.alpn_offers = tuple(client.alpn_offers)
|
| 444 |
+
else:
|
| 445 |
+
# aioquic fails if no ALPN is offered, so use H3
|
| 446 |
+
server.alpn_offers = tuple(alpn.encode("ascii") for alpn in H3_ALPN)
|
| 447 |
+
|
| 448 |
+
if not server.cipher_list and ctx.options.ciphers_server:
|
| 449 |
+
server.cipher_list = ctx.options.ciphers_server.split(":")
|
| 450 |
+
|
| 451 |
+
# set context parameters
|
| 452 |
+
if server.cipher_list:
|
| 453 |
+
tls_start.settings.cipher_suites = [
|
| 454 |
+
CipherSuite[cipher] for cipher in server.cipher_list
|
| 455 |
+
]
|
| 456 |
+
if server.alpn_offers:
|
| 457 |
+
tls_start.settings.alpn_protocols = [
|
| 458 |
+
alpn.decode("ascii") for alpn in server.alpn_offers
|
| 459 |
+
]
|
| 460 |
+
|
| 461 |
+
# set the certificates
|
| 462 |
+
# NOTE client certificates are not supported
|
| 463 |
+
tls_start.settings.ca_path = ctx.options.ssl_verify_upstream_trusted_confdir
|
| 464 |
+
tls_start.settings.ca_file = ctx.options.ssl_verify_upstream_trusted_ca
|
| 465 |
+
|
| 466 |
+
def running(self):
|
| 467 |
+
# FIXME: We have a weird bug where the contract for configure is not followed and it is never called with
|
| 468 |
+
# confdir or command_history as updated.
|
| 469 |
+
self.configure("confdir") # pragma: no cover
|
| 470 |
+
|
| 471 |
+
def configure(self, updated):
|
| 472 |
+
if (
|
| 473 |
+
"certs" in updated
|
| 474 |
+
or "confdir" in updated
|
| 475 |
+
or "key_size" in updated
|
| 476 |
+
or "cert_passphrase" in updated
|
| 477 |
+
):
|
| 478 |
+
certstore_path = os.path.expanduser(ctx.options.confdir)
|
| 479 |
+
self.certstore = certs.CertStore.from_store(
|
| 480 |
+
path=certstore_path,
|
| 481 |
+
basename=CONF_BASENAME,
|
| 482 |
+
key_size=ctx.options.key_size,
|
| 483 |
+
passphrase=ctx.options.cert_passphrase.encode("utf8")
|
| 484 |
+
if ctx.options.cert_passphrase
|
| 485 |
+
else None,
|
| 486 |
+
)
|
| 487 |
+
if self.certstore.default_ca.has_expired():
|
| 488 |
+
logger.warning(
|
| 489 |
+
"The mitmproxy certificate authority has expired!\n"
|
| 490 |
+
"Please delete all CA-related files in your ~/.mitmproxy folder.\n"
|
| 491 |
+
"The CA will be regenerated automatically after restarting mitmproxy.\n"
|
| 492 |
+
"See https://docs.mitmproxy.org/stable/concepts-certificates/ for additional help.",
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
for certspec in ctx.options.certs:
|
| 496 |
+
parts = certspec.split("=", 1)
|
| 497 |
+
if len(parts) == 1:
|
| 498 |
+
parts = ["*", parts[0]]
|
| 499 |
+
|
| 500 |
+
cert = Path(parts[1]).expanduser()
|
| 501 |
+
if not cert.exists():
|
| 502 |
+
raise exceptions.OptionsError(
|
| 503 |
+
f"Certificate file does not exist: {cert}"
|
| 504 |
+
)
|
| 505 |
+
try:
|
| 506 |
+
self.certstore.add_cert_file(
|
| 507 |
+
parts[0],
|
| 508 |
+
cert,
|
| 509 |
+
passphrase=ctx.options.cert_passphrase.encode("utf8")
|
| 510 |
+
if ctx.options.cert_passphrase
|
| 511 |
+
else None,
|
| 512 |
+
)
|
| 513 |
+
except ValueError as e:
|
| 514 |
+
raise exceptions.OptionsError(
|
| 515 |
+
f"Invalid certificate format for {cert}: {e}"
|
| 516 |
+
) from e
|
| 517 |
+
|
| 518 |
+
if "tls_ecdh_curve_client" in updated or "tls_ecdh_curve_server" in updated:
|
| 519 |
+
for ecdh_curve in [
|
| 520 |
+
ctx.options.tls_ecdh_curve_client,
|
| 521 |
+
ctx.options.tls_ecdh_curve_server,
|
| 522 |
+
]:
|
| 523 |
+
if ecdh_curve is not None and ecdh_curve not in net_tls.EC_CURVES:
|
| 524 |
+
raise exceptions.OptionsError(
|
| 525 |
+
f"Invalid ECDH curve: {ecdh_curve!r}. Valid curves are: {', '.join(net_tls.EC_CURVES)}"
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
if "tls_version_client_min" in updated:
|
| 529 |
+
self._warn_unsupported_version("tls_version_client_min", True)
|
| 530 |
+
if "tls_version_client_max" in updated:
|
| 531 |
+
self._warn_unsupported_version("tls_version_client_max", False)
|
| 532 |
+
if "tls_version_server_min" in updated:
|
| 533 |
+
self._warn_unsupported_version("tls_version_server_min", True)
|
| 534 |
+
if "tls_version_server_max" in updated:
|
| 535 |
+
self._warn_unsupported_version("tls_version_server_max", False)
|
| 536 |
+
if "tls_version_client_min" in updated or "ciphers_client" in updated:
|
| 537 |
+
self._warn_seclevel_missing("client")
|
| 538 |
+
if "tls_version_server_min" in updated or "ciphers_server" in updated:
|
| 539 |
+
self._warn_seclevel_missing("server")
|
| 540 |
+
|
| 541 |
+
def _warn_unsupported_version(self, attribute: str, warn_unbound: bool):
|
| 542 |
+
val = net_tls.Version[getattr(ctx.options, attribute)]
|
| 543 |
+
supported_versions = [
|
| 544 |
+
v for v in net_tls.Version if net_tls.is_supported_version(v)
|
| 545 |
+
]
|
| 546 |
+
supported_versions_str = ", ".join(v.name for v in supported_versions)
|
| 547 |
+
|
| 548 |
+
if val is net_tls.Version.UNBOUNDED:
|
| 549 |
+
if warn_unbound:
|
| 550 |
+
logger.info(
|
| 551 |
+
f"{attribute} has been set to {val.name}. Note that your "
|
| 552 |
+
f"OpenSSL build only supports the following TLS versions: {supported_versions_str}"
|
| 553 |
+
)
|
| 554 |
+
elif val not in supported_versions:
|
| 555 |
+
logger.warning(
|
| 556 |
+
f"{attribute} has been set to {val.name}, which is not supported by the current OpenSSL build. "
|
| 557 |
+
f"The current build only supports the following versions: {supported_versions_str}"
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
def _warn_seclevel_missing(self, side: Literal["client", "server"]) -> None:
|
| 561 |
+
"""
|
| 562 |
+
OpenSSL cipher spec need to specify @SECLEVEL for old TLS versions to work,
|
| 563 |
+
see https://github.com/pyca/cryptography/issues/9523.
|
| 564 |
+
"""
|
| 565 |
+
if side == "client":
|
| 566 |
+
custom_ciphers = ctx.options.ciphers_client
|
| 567 |
+
min_tls_version = ctx.options.tls_version_client_min
|
| 568 |
+
else:
|
| 569 |
+
custom_ciphers = ctx.options.ciphers_server
|
| 570 |
+
min_tls_version = ctx.options.tls_version_server_min
|
| 571 |
+
|
| 572 |
+
if (
|
| 573 |
+
custom_ciphers
|
| 574 |
+
and net_tls.Version[min_tls_version] in net_tls.INSECURE_TLS_MIN_VERSIONS
|
| 575 |
+
and "@SECLEVEL=0" not in custom_ciphers
|
| 576 |
+
):
|
| 577 |
+
logger.warning(
|
| 578 |
+
f'With tls_version_{side}_min set to {min_tls_version}, ciphers_{side} must include "@SECLEVEL=0" '
|
| 579 |
+
f"for insecure TLS versions to work."
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
def crl_path(self) -> str:
|
| 583 |
+
return f"/mitmproxy-{self.certstore.default_ca.serial}.crl"
|
| 584 |
+
|
| 585 |
+
def get_cert(self, conn_context: context.Context) -> certs.CertStoreEntry:
|
| 586 |
+
"""
|
| 587 |
+
This function determines the Common Name (CN), Subject Alternative Names (SANs) and Organization Name
|
| 588 |
+
our certificate should have and then fetches a matching cert from the certstore.
|
| 589 |
+
"""
|
| 590 |
+
altnames: list[x509.GeneralName] = []
|
| 591 |
+
organization: str | None = None
|
| 592 |
+
crl_distribution_point: str | None = None
|
| 593 |
+
|
| 594 |
+
# Use upstream certificate if available.
|
| 595 |
+
if ctx.options.upstream_cert and conn_context.server.certificate_list:
|
| 596 |
+
upstream_cert: certs.Cert = conn_context.server.certificate_list[0]
|
| 597 |
+
if upstream_cert.cn:
|
| 598 |
+
altnames.append(_ip_or_dns_name(upstream_cert.cn))
|
| 599 |
+
altnames.extend(upstream_cert.altnames)
|
| 600 |
+
if upstream_cert.organization:
|
| 601 |
+
organization = upstream_cert.organization
|
| 602 |
+
|
| 603 |
+
# Replace original URL path with the CA cert serial number, which acts as a magic token
|
| 604 |
+
if crls := upstream_cert.crl_distribution_points:
|
| 605 |
+
try:
|
| 606 |
+
scheme, netloc, *_ = urllib.parse.urlsplit(crls[0])
|
| 607 |
+
except ValueError:
|
| 608 |
+
logger.info(f"Failed to parse CRL URL: {crls[0]!r}")
|
| 609 |
+
else:
|
| 610 |
+
# noinspection PyTypeChecker
|
| 611 |
+
crl_distribution_point = urllib.parse.urlunsplit(
|
| 612 |
+
(scheme, netloc, self.crl_path(), None, None)
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
# Add SNI or our local IP address.
|
| 616 |
+
if conn_context.client.sni:
|
| 617 |
+
altnames.append(_ip_or_dns_name(conn_context.client.sni))
|
| 618 |
+
else:
|
| 619 |
+
altnames.append(_ip_or_dns_name(conn_context.client.sockname[0]))
|
| 620 |
+
|
| 621 |
+
# If we already know of a server address, include that in the SANs as well.
|
| 622 |
+
if conn_context.server.address:
|
| 623 |
+
altnames.append(_ip_or_dns_name(conn_context.server.address[0]))
|
| 624 |
+
|
| 625 |
+
# only keep first occurrence of each hostname
|
| 626 |
+
altnames = list(dict.fromkeys(altnames))
|
| 627 |
+
|
| 628 |
+
# RFC 2818: If a subjectAltName extension of type dNSName is present, that MUST be used as the identity.
|
| 629 |
+
# In other words, the Common Name is irrelevant then.
|
| 630 |
+
cn = next((str(x.value) for x in altnames), None)
|
| 631 |
+
return self.certstore.get_cert(
|
| 632 |
+
cn, altnames, organization, crl_distribution_point
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
def request(self, flow: http.HTTPFlow):
|
| 636 |
+
if not flow.live or flow.error or flow.response:
|
| 637 |
+
return
|
| 638 |
+
# Check if a request has a magic CRL token at the end
|
| 639 |
+
if flow.request.path.endswith(self.crl_path()):
|
| 640 |
+
flow.response = http.Response.make(
|
| 641 |
+
200,
|
| 642 |
+
self.certstore.default_crl,
|
| 643 |
+
{"Content-Type": "application/pkix-crl"},
|
| 644 |
+
)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def _ip_or_dns_name(val: str) -> x509.GeneralName:
|
| 648 |
+
"""Convert a string into either an x509.IPAddress or x509.DNSName object."""
|
| 649 |
+
try:
|
| 650 |
+
ip = ipaddress.ip_address(val)
|
| 651 |
+
except ValueError:
|
| 652 |
+
return x509.DNSName(val.encode("idna").decode())
|
| 653 |
+
else:
|
| 654 |
+
return x509.IPAddress(ip)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/update_alt_svc.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
from mitmproxy import ctx
|
| 4 |
+
from mitmproxy.http import HTTPFlow
|
| 5 |
+
from mitmproxy.proxy import mode_specs
|
| 6 |
+
|
| 7 |
+
ALT_SVC = "alt-svc"
|
| 8 |
+
HOST_PATTERN = r"([a-zA-Z0-9.-]*:\d{1,5})"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def update_alt_svc_header(header: str, port: int) -> str:
|
| 12 |
+
return re.sub(HOST_PATTERN, f":{port}", header)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class UpdateAltSvc:
|
| 16 |
+
def load(self, loader):
|
| 17 |
+
loader.add_option(
|
| 18 |
+
"keep_alt_svc_header",
|
| 19 |
+
bool,
|
| 20 |
+
False,
|
| 21 |
+
"Reverse Proxy: Keep Alt-Svc headers as-is, even if they do not point to mitmproxy. Enabling this option may cause clients to bypass the proxy.",
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
def responseheaders(self, flow: HTTPFlow):
|
| 25 |
+
assert flow.response
|
| 26 |
+
if (
|
| 27 |
+
not ctx.options.keep_alt_svc_header
|
| 28 |
+
and isinstance(flow.client_conn.proxy_mode, mode_specs.ReverseMode)
|
| 29 |
+
and ALT_SVC in flow.response.headers
|
| 30 |
+
):
|
| 31 |
+
_, listen_port, *_ = flow.client_conn.sockname
|
| 32 |
+
headers = flow.response.headers
|
| 33 |
+
headers[ALT_SVC] = update_alt_svc_header(headers[ALT_SVC], listen_port)
|
python/user_packages/Python313/site-packages/mitmproxy/addons/upstream_auth.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import re
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from mitmproxy import ctx
|
| 6 |
+
from mitmproxy import exceptions
|
| 7 |
+
from mitmproxy import http
|
| 8 |
+
from mitmproxy.proxy import mode_specs
|
| 9 |
+
from mitmproxy.utils import strutils
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parse_upstream_auth(auth: str) -> bytes:
|
| 13 |
+
pattern = re.compile(".+:")
|
| 14 |
+
if pattern.search(auth) is None:
|
| 15 |
+
raise exceptions.OptionsError("Invalid upstream auth specification: %s" % auth)
|
| 16 |
+
return b"Basic" + b" " + base64.b64encode(strutils.always_bytes(auth))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class UpstreamAuth:
|
| 20 |
+
"""
|
| 21 |
+
This addon handles authentication to systems upstream from us for the
|
| 22 |
+
upstream proxy and reverse proxy mode. There are 3 cases:
|
| 23 |
+
|
| 24 |
+
- Upstream proxy CONNECT requests should have authentication added, and
|
| 25 |
+
subsequent already connected requests should not.
|
| 26 |
+
- Upstream proxy regular requests
|
| 27 |
+
- Reverse proxy regular requests (CONNECT is invalid in this mode)
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
auth: bytes | None = None
|
| 31 |
+
|
| 32 |
+
def load(self, loader):
|
| 33 |
+
loader.add_option(
|
| 34 |
+
"upstream_auth",
|
| 35 |
+
Optional[str],
|
| 36 |
+
None,
|
| 37 |
+
"""
|
| 38 |
+
Add HTTP Basic authentication to upstream proxy and reverse proxy
|
| 39 |
+
requests. Format: username:password.
|
| 40 |
+
""",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
def configure(self, updated):
|
| 44 |
+
if "upstream_auth" in updated:
|
| 45 |
+
if ctx.options.upstream_auth is None:
|
| 46 |
+
self.auth = None
|
| 47 |
+
else:
|
| 48 |
+
self.auth = parse_upstream_auth(ctx.options.upstream_auth)
|
| 49 |
+
|
| 50 |
+
def http_connect_upstream(self, f: http.HTTPFlow):
|
| 51 |
+
if self.auth:
|
| 52 |
+
f.request.headers["Proxy-Authorization"] = self.auth
|
| 53 |
+
|
| 54 |
+
def requestheaders(self, f: http.HTTPFlow):
|
| 55 |
+
if self.auth:
|
| 56 |
+
if (
|
| 57 |
+
isinstance(f.client_conn.proxy_mode, mode_specs.UpstreamMode)
|
| 58 |
+
and f.request.scheme == "http"
|
| 59 |
+
):
|
| 60 |
+
f.request.headers["Proxy-Authorization"] = self.auth
|
| 61 |
+
elif isinstance(f.client_conn.proxy_mode, mode_specs.ReverseMode):
|
| 62 |
+
f.request.headers["Authorization"] = self.auth
|
python/user_packages/Python313/site-packages/mitmproxy/addons/view.py
ADDED
|
@@ -0,0 +1,749 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The View:
|
| 3 |
+
|
| 4 |
+
- Keeps track of a store of flows
|
| 5 |
+
- Maintains a filtered, ordered view onto that list of flows
|
| 6 |
+
- Exposes a number of signals so the view can be monitored
|
| 7 |
+
- Tracks focus within the view
|
| 8 |
+
- Exposes a settings store for flows that automatically expires if the flow is
|
| 9 |
+
removed from the store.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import collections
|
| 13 |
+
import logging
|
| 14 |
+
import re
|
| 15 |
+
from collections.abc import Iterator
|
| 16 |
+
from collections.abc import MutableMapping
|
| 17 |
+
from collections.abc import Sequence
|
| 18 |
+
from typing import Any
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
import sortedcontainers
|
| 22 |
+
|
| 23 |
+
import mitmproxy.flow
|
| 24 |
+
from mitmproxy import command
|
| 25 |
+
from mitmproxy import connection
|
| 26 |
+
from mitmproxy import ctx
|
| 27 |
+
from mitmproxy import dns
|
| 28 |
+
from mitmproxy import exceptions
|
| 29 |
+
from mitmproxy import flowfilter
|
| 30 |
+
from mitmproxy import hooks
|
| 31 |
+
from mitmproxy import http
|
| 32 |
+
from mitmproxy import io
|
| 33 |
+
from mitmproxy import tcp
|
| 34 |
+
from mitmproxy import udp
|
| 35 |
+
from mitmproxy.log import ALERT
|
| 36 |
+
from mitmproxy.utils import human
|
| 37 |
+
from mitmproxy.utils import signals
|
| 38 |
+
|
| 39 |
+
# The underlying sorted list implementation expects the sort key to be stable
|
| 40 |
+
# for the lifetime of the object. However, if we sort by size, for instance,
|
| 41 |
+
# the sort order changes as the flow progresses through its lifecycle. We
|
| 42 |
+
# address this through two means:
|
| 43 |
+
#
|
| 44 |
+
# - Let order keys cache the sort value by flow ID.
|
| 45 |
+
#
|
| 46 |
+
# - Add a facility to refresh items in the list by removing and re-adding them
|
| 47 |
+
# when they are updated.
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class _OrderKey:
|
| 51 |
+
def __init__(self, view):
|
| 52 |
+
self.view = view
|
| 53 |
+
|
| 54 |
+
def generate(self, f: mitmproxy.flow.Flow) -> Any: # pragma: no cover
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
def refresh(self, f):
|
| 58 |
+
k = self._key()
|
| 59 |
+
old = self.view.settings[f][k]
|
| 60 |
+
new = self.generate(f)
|
| 61 |
+
if old != new:
|
| 62 |
+
self.view._view.remove(f)
|
| 63 |
+
self.view.settings[f][k] = new
|
| 64 |
+
self.view._view.add(f)
|
| 65 |
+
self.view.sig_view_refresh.send()
|
| 66 |
+
|
| 67 |
+
def _key(self):
|
| 68 |
+
return "_order_%s" % id(self)
|
| 69 |
+
|
| 70 |
+
def __call__(self, f):
|
| 71 |
+
if f.id in self.view._store:
|
| 72 |
+
k = self._key()
|
| 73 |
+
s = self.view.settings[f]
|
| 74 |
+
if k in s:
|
| 75 |
+
return s[k]
|
| 76 |
+
val = self.generate(f)
|
| 77 |
+
s[k] = val
|
| 78 |
+
return val
|
| 79 |
+
else:
|
| 80 |
+
return self.generate(f)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class OrderRequestStart(_OrderKey):
|
| 84 |
+
def generate(self, f: mitmproxy.flow.Flow) -> float:
|
| 85 |
+
return f.timestamp_created
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class OrderRequestMethod(_OrderKey):
|
| 89 |
+
def generate(self, f: mitmproxy.flow.Flow) -> str:
|
| 90 |
+
if isinstance(f, http.HTTPFlow):
|
| 91 |
+
return f.request.method
|
| 92 |
+
elif isinstance(f, (tcp.TCPFlow, udp.UDPFlow)):
|
| 93 |
+
return f.type.upper()
|
| 94 |
+
elif isinstance(f, dns.DNSFlow):
|
| 95 |
+
return dns.op_codes.to_str(f.request.op_code)
|
| 96 |
+
else:
|
| 97 |
+
raise NotImplementedError()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class OrderRequestURL(_OrderKey):
|
| 101 |
+
def generate(self, f: mitmproxy.flow.Flow) -> str:
|
| 102 |
+
if isinstance(f, http.HTTPFlow):
|
| 103 |
+
return f.request.url
|
| 104 |
+
elif isinstance(f, (tcp.TCPFlow, udp.UDPFlow)):
|
| 105 |
+
return human.format_address(f.server_conn.address)
|
| 106 |
+
elif isinstance(f, dns.DNSFlow):
|
| 107 |
+
return f.request.questions[0].name if f.request.questions else ""
|
| 108 |
+
else:
|
| 109 |
+
raise NotImplementedError()
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class OrderKeySize(_OrderKey):
|
| 113 |
+
def generate(self, f: mitmproxy.flow.Flow) -> int:
|
| 114 |
+
if isinstance(f, http.HTTPFlow):
|
| 115 |
+
size = 0
|
| 116 |
+
if f.request.raw_content:
|
| 117 |
+
size += len(f.request.raw_content)
|
| 118 |
+
if f.response and f.response.raw_content:
|
| 119 |
+
size += len(f.response.raw_content)
|
| 120 |
+
return size
|
| 121 |
+
elif isinstance(f, (tcp.TCPFlow, udp.UDPFlow)):
|
| 122 |
+
size = 0
|
| 123 |
+
for message in f.messages:
|
| 124 |
+
size += len(message.content)
|
| 125 |
+
return size
|
| 126 |
+
elif isinstance(f, dns.DNSFlow):
|
| 127 |
+
return f.response.size if f.response else 0
|
| 128 |
+
else:
|
| 129 |
+
raise NotImplementedError()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
orders = [
|
| 133 |
+
("t", "time"),
|
| 134 |
+
("m", "method"),
|
| 135 |
+
("u", "url"),
|
| 136 |
+
("z", "size"),
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _signal_with_flow(flow: mitmproxy.flow.Flow) -> None: ...
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _sig_view_remove(flow: mitmproxy.flow.Flow, index: int) -> None: ...
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class View(collections.abc.Sequence):
|
| 147 |
+
def __init__(self) -> None:
|
| 148 |
+
super().__init__()
|
| 149 |
+
self._store: collections.OrderedDict[str, mitmproxy.flow.Flow] = (
|
| 150 |
+
collections.OrderedDict()
|
| 151 |
+
)
|
| 152 |
+
self.filter = flowfilter.match_all
|
| 153 |
+
# Should we show only marked flows?
|
| 154 |
+
self.show_marked = False
|
| 155 |
+
|
| 156 |
+
self.default_order = OrderRequestStart(self)
|
| 157 |
+
self.orders = dict(
|
| 158 |
+
time=OrderRequestStart(self),
|
| 159 |
+
method=OrderRequestMethod(self),
|
| 160 |
+
url=OrderRequestURL(self),
|
| 161 |
+
size=OrderKeySize(self),
|
| 162 |
+
)
|
| 163 |
+
self.order_key: _OrderKey = self.default_order
|
| 164 |
+
self.order_reversed = False
|
| 165 |
+
self.focus_follow = False
|
| 166 |
+
|
| 167 |
+
self._view = sortedcontainers.SortedListWithKey(key=self.order_key)
|
| 168 |
+
|
| 169 |
+
# The sig_view* signals broadcast events that affect the view. That is,
|
| 170 |
+
# an update to a flow in the store but not in the view does not trigger
|
| 171 |
+
# a signal. All signals are called after the view has been updated.
|
| 172 |
+
self.sig_view_update = signals.SyncSignal(_signal_with_flow)
|
| 173 |
+
self.sig_view_add = signals.SyncSignal(_signal_with_flow)
|
| 174 |
+
self.sig_view_remove = signals.SyncSignal(_sig_view_remove)
|
| 175 |
+
# Signals that the view should be refreshed completely
|
| 176 |
+
self.sig_view_refresh = signals.SyncSignal(lambda: None)
|
| 177 |
+
|
| 178 |
+
# The sig_store* signals broadcast events that affect the underlying
|
| 179 |
+
# store. If a flow is removed from just the view, sig_view_remove is
|
| 180 |
+
# triggered. If it is removed from the store while it is also in the
|
| 181 |
+
# view, both sig_store_remove and sig_view_remove are triggered.
|
| 182 |
+
self.sig_store_remove = signals.SyncSignal(_signal_with_flow)
|
| 183 |
+
# Signals that the store should be refreshed completely
|
| 184 |
+
self.sig_store_refresh = signals.SyncSignal(lambda: None)
|
| 185 |
+
|
| 186 |
+
self.focus = Focus(self)
|
| 187 |
+
self.settings = Settings(self)
|
| 188 |
+
|
| 189 |
+
def load(self, loader):
|
| 190 |
+
loader.add_option(
|
| 191 |
+
"view_filter", Optional[str], None, "Limit the view to matching flows."
|
| 192 |
+
)
|
| 193 |
+
loader.add_option(
|
| 194 |
+
"view_order",
|
| 195 |
+
str,
|
| 196 |
+
"time",
|
| 197 |
+
"Flow sort order.",
|
| 198 |
+
choices=list(map(lambda c: c[1], orders)),
|
| 199 |
+
)
|
| 200 |
+
loader.add_option(
|
| 201 |
+
"view_order_reversed", bool, False, "Reverse the sorting order."
|
| 202 |
+
)
|
| 203 |
+
loader.add_option(
|
| 204 |
+
"console_focus_follow", bool, False, "Focus follows new flows."
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
def store_count(self):
|
| 208 |
+
return len(self._store)
|
| 209 |
+
|
| 210 |
+
def _rev(self, idx: int) -> int:
|
| 211 |
+
"""
|
| 212 |
+
Reverses an index, if needed
|
| 213 |
+
"""
|
| 214 |
+
if self.order_reversed:
|
| 215 |
+
if idx < 0:
|
| 216 |
+
idx = -idx - 1
|
| 217 |
+
else:
|
| 218 |
+
idx = len(self._view) - idx - 1
|
| 219 |
+
if idx < 0:
|
| 220 |
+
raise IndexError
|
| 221 |
+
return idx
|
| 222 |
+
|
| 223 |
+
def __len__(self):
|
| 224 |
+
return len(self._view)
|
| 225 |
+
|
| 226 |
+
def __getitem__(self, offset) -> Any:
|
| 227 |
+
return self._view[self._rev(offset)]
|
| 228 |
+
|
| 229 |
+
# Reflect some methods to the efficient underlying implementation
|
| 230 |
+
|
| 231 |
+
def _bisect(self, f: mitmproxy.flow.Flow) -> int:
|
| 232 |
+
v = self._view.bisect_right(f)
|
| 233 |
+
return self._rev(v - 1) + 1
|
| 234 |
+
|
| 235 |
+
def index(
|
| 236 |
+
self, f: mitmproxy.flow.Flow, start: int = 0, stop: int | None = None
|
| 237 |
+
) -> int:
|
| 238 |
+
return self._rev(self._view.index(f, start, stop))
|
| 239 |
+
|
| 240 |
+
def __contains__(self, f: Any) -> bool:
|
| 241 |
+
return self._view.__contains__(f)
|
| 242 |
+
|
| 243 |
+
def _order_key_name(self):
|
| 244 |
+
return "_order_%s" % id(self.order_key)
|
| 245 |
+
|
| 246 |
+
def _base_add(self, f):
|
| 247 |
+
self.settings[f][self._order_key_name()] = self.order_key(f)
|
| 248 |
+
self._view.add(f)
|
| 249 |
+
|
| 250 |
+
def _refilter(self):
|
| 251 |
+
self._view.clear()
|
| 252 |
+
for i in self._store.values():
|
| 253 |
+
if self.show_marked and not i.marked:
|
| 254 |
+
continue
|
| 255 |
+
if self.filter(i):
|
| 256 |
+
self._base_add(i)
|
| 257 |
+
self.sig_view_refresh.send()
|
| 258 |
+
|
| 259 |
+
""" View API """
|
| 260 |
+
|
| 261 |
+
# Focus
|
| 262 |
+
@command.command("view.focus.go")
|
| 263 |
+
def go(self, offset: int) -> None:
|
| 264 |
+
"""
|
| 265 |
+
Go to a specified offset. Positive offests are from the beginning of
|
| 266 |
+
the view, negative from the end of the view, so that 0 is the first
|
| 267 |
+
flow, -1 is the last flow.
|
| 268 |
+
"""
|
| 269 |
+
if len(self) == 0:
|
| 270 |
+
return
|
| 271 |
+
if offset < 0:
|
| 272 |
+
offset = len(self) + offset
|
| 273 |
+
if offset < 0:
|
| 274 |
+
offset = 0
|
| 275 |
+
if offset > len(self) - 1:
|
| 276 |
+
offset = len(self) - 1
|
| 277 |
+
self.focus.flow = self[offset]
|
| 278 |
+
|
| 279 |
+
@command.command("view.focus.next")
|
| 280 |
+
def focus_next(self) -> None:
|
| 281 |
+
"""
|
| 282 |
+
Set focus to the next flow.
|
| 283 |
+
"""
|
| 284 |
+
if self.focus.index is not None:
|
| 285 |
+
idx = self.focus.index + 1
|
| 286 |
+
if self.inbounds(idx):
|
| 287 |
+
self.focus.flow = self[idx]
|
| 288 |
+
else:
|
| 289 |
+
pass
|
| 290 |
+
|
| 291 |
+
@command.command("view.focus.prev")
|
| 292 |
+
def focus_prev(self) -> None:
|
| 293 |
+
"""
|
| 294 |
+
Set focus to the previous flow.
|
| 295 |
+
"""
|
| 296 |
+
if self.focus.index is not None:
|
| 297 |
+
idx = self.focus.index - 1
|
| 298 |
+
if self.inbounds(idx):
|
| 299 |
+
self.focus.flow = self[idx]
|
| 300 |
+
else:
|
| 301 |
+
pass
|
| 302 |
+
|
| 303 |
+
# Order
|
| 304 |
+
@command.command("view.order.options")
|
| 305 |
+
def order_options(self) -> Sequence[str]:
|
| 306 |
+
"""
|
| 307 |
+
Choices supported by the view_order option.
|
| 308 |
+
"""
|
| 309 |
+
return list(sorted(self.orders.keys()))
|
| 310 |
+
|
| 311 |
+
@command.command("view.order.reverse")
|
| 312 |
+
def set_reversed(self, boolean: bool) -> None:
|
| 313 |
+
self.order_reversed = boolean
|
| 314 |
+
self.sig_view_refresh.send()
|
| 315 |
+
|
| 316 |
+
@command.command("view.order.set")
|
| 317 |
+
def set_order(self, order_key: str) -> None:
|
| 318 |
+
"""
|
| 319 |
+
Sets the current view order.
|
| 320 |
+
"""
|
| 321 |
+
if order_key not in self.orders:
|
| 322 |
+
raise exceptions.CommandError("Unknown flow order: %s" % order_key)
|
| 323 |
+
key = self.orders[order_key]
|
| 324 |
+
self.order_key = key
|
| 325 |
+
newview = sortedcontainers.SortedListWithKey(key=key)
|
| 326 |
+
newview.update(self._view)
|
| 327 |
+
self._view = newview
|
| 328 |
+
|
| 329 |
+
@command.command("view.order")
|
| 330 |
+
def get_order(self) -> str:
|
| 331 |
+
"""
|
| 332 |
+
Returns the current view order.
|
| 333 |
+
"""
|
| 334 |
+
order = ""
|
| 335 |
+
for k in self.orders.keys():
|
| 336 |
+
if self.order_key == self.orders[k]:
|
| 337 |
+
order = k
|
| 338 |
+
return order
|
| 339 |
+
|
| 340 |
+
# Filter
|
| 341 |
+
@command.command("view.filter.set")
|
| 342 |
+
def set_filter_cmd(self, filter_expr: str) -> None:
|
| 343 |
+
"""
|
| 344 |
+
Sets the current view filter.
|
| 345 |
+
"""
|
| 346 |
+
filt = None
|
| 347 |
+
if filter_expr:
|
| 348 |
+
try:
|
| 349 |
+
filt = flowfilter.parse(filter_expr)
|
| 350 |
+
except ValueError as e:
|
| 351 |
+
raise exceptions.CommandError(str(e)) from e
|
| 352 |
+
self.set_filter(filt)
|
| 353 |
+
|
| 354 |
+
def set_filter(self, flt: flowfilter.TFilter | None):
|
| 355 |
+
self.filter = flt or flowfilter.match_all
|
| 356 |
+
self._refilter()
|
| 357 |
+
|
| 358 |
+
# View Updates
|
| 359 |
+
@command.command("view.clear")
|
| 360 |
+
def clear(self) -> None:
|
| 361 |
+
"""
|
| 362 |
+
Clears both the store and view.
|
| 363 |
+
"""
|
| 364 |
+
self._store.clear()
|
| 365 |
+
self._view.clear()
|
| 366 |
+
self.sig_view_refresh.send()
|
| 367 |
+
self.sig_store_refresh.send()
|
| 368 |
+
|
| 369 |
+
@command.command("view.clear_unmarked")
|
| 370 |
+
def clear_not_marked(self) -> None:
|
| 371 |
+
"""
|
| 372 |
+
Clears only the unmarked flows.
|
| 373 |
+
"""
|
| 374 |
+
for flow in self._store.copy().values():
|
| 375 |
+
if not flow.marked:
|
| 376 |
+
self._store.pop(flow.id)
|
| 377 |
+
|
| 378 |
+
self._refilter()
|
| 379 |
+
self.sig_store_refresh.send()
|
| 380 |
+
|
| 381 |
+
# View Settings
|
| 382 |
+
@command.command("view.settings.getval")
|
| 383 |
+
def getvalue(self, flow: mitmproxy.flow.Flow, key: str, default: str) -> str:
|
| 384 |
+
"""
|
| 385 |
+
Get a value from the settings store for the specified flow.
|
| 386 |
+
"""
|
| 387 |
+
return self.settings[flow].get(key, default)
|
| 388 |
+
|
| 389 |
+
@command.command("view.settings.setval.toggle")
|
| 390 |
+
def setvalue_toggle(self, flows: Sequence[mitmproxy.flow.Flow], key: str) -> None:
|
| 391 |
+
"""
|
| 392 |
+
Toggle a boolean value in the settings store, setting the value to
|
| 393 |
+
the string "true" or "false".
|
| 394 |
+
"""
|
| 395 |
+
updated = []
|
| 396 |
+
for f in flows:
|
| 397 |
+
current = self.settings[f].get(key, "false")
|
| 398 |
+
self.settings[f][key] = "false" if current == "true" else "true"
|
| 399 |
+
updated.append(f)
|
| 400 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 401 |
+
|
| 402 |
+
@command.command("view.settings.setval")
|
| 403 |
+
def setvalue(
|
| 404 |
+
self, flows: Sequence[mitmproxy.flow.Flow], key: str, value: str
|
| 405 |
+
) -> None:
|
| 406 |
+
"""
|
| 407 |
+
Set a value in the settings store for the specified flows.
|
| 408 |
+
"""
|
| 409 |
+
updated = []
|
| 410 |
+
for f in flows:
|
| 411 |
+
self.settings[f][key] = value
|
| 412 |
+
updated.append(f)
|
| 413 |
+
ctx.master.addons.trigger(hooks.UpdateHook(updated))
|
| 414 |
+
|
| 415 |
+
# Flows
|
| 416 |
+
@command.command("view.flows.duplicate")
|
| 417 |
+
def duplicate(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
|
| 418 |
+
"""
|
| 419 |
+
Duplicates the specified flows, and sets the focus to the first
|
| 420 |
+
duplicate.
|
| 421 |
+
"""
|
| 422 |
+
dups = [f.copy() for f in flows]
|
| 423 |
+
if dups:
|
| 424 |
+
self.add(dups)
|
| 425 |
+
self.focus.flow = dups[0]
|
| 426 |
+
logging.log(ALERT, "Duplicated %s flows" % len(dups))
|
| 427 |
+
|
| 428 |
+
@command.command("view.flows.remove")
|
| 429 |
+
def remove(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
|
| 430 |
+
"""
|
| 431 |
+
Removes the flow from the underlying store and the view.
|
| 432 |
+
"""
|
| 433 |
+
for f in flows:
|
| 434 |
+
if f.id in self._store:
|
| 435 |
+
if f.killable:
|
| 436 |
+
f.kill()
|
| 437 |
+
if f in self._view:
|
| 438 |
+
# We manually pass the index here because multiple flows may have the same
|
| 439 |
+
# sorting key, and we cannot reconstruct the index from that.
|
| 440 |
+
idx = self._view.index(f)
|
| 441 |
+
self._view.remove(f)
|
| 442 |
+
self.sig_view_remove.send(flow=f, index=idx)
|
| 443 |
+
del self._store[f.id]
|
| 444 |
+
self.sig_store_remove.send(flow=f)
|
| 445 |
+
if len(flows) > 1:
|
| 446 |
+
logging.log(ALERT, "Removed %s flows" % len(flows))
|
| 447 |
+
|
| 448 |
+
@command.command("view.flows.resolve")
|
| 449 |
+
def resolve(self, flow_spec: str) -> Sequence[mitmproxy.flow.Flow]:
|
| 450 |
+
"""
|
| 451 |
+
Resolve a flow list specification to an actual list of flows.
|
| 452 |
+
"""
|
| 453 |
+
if flow_spec == "@all":
|
| 454 |
+
return [i for i in self._store.values()]
|
| 455 |
+
if flow_spec == "@focus":
|
| 456 |
+
return [self.focus.flow] if self.focus.flow else []
|
| 457 |
+
elif flow_spec == "@shown":
|
| 458 |
+
return [i for i in self]
|
| 459 |
+
elif flow_spec == "@hidden":
|
| 460 |
+
return [i for i in self._store.values() if i not in self._view]
|
| 461 |
+
elif flow_spec == "@marked":
|
| 462 |
+
return [i for i in self._store.values() if i.marked]
|
| 463 |
+
elif flow_spec == "@unmarked":
|
| 464 |
+
return [i for i in self._store.values() if not i.marked]
|
| 465 |
+
elif re.match(r"@[0-9a-f\-,]{36,}", flow_spec):
|
| 466 |
+
ids = flow_spec[1:].split(",")
|
| 467 |
+
return [i for i in self._store.values() if i.id in ids]
|
| 468 |
+
else:
|
| 469 |
+
try:
|
| 470 |
+
filt = flowfilter.parse(flow_spec)
|
| 471 |
+
except ValueError as e:
|
| 472 |
+
raise exceptions.CommandError(str(e)) from e
|
| 473 |
+
return [i for i in self._store.values() if filt(i)]
|
| 474 |
+
|
| 475 |
+
@command.command("view.flows.create")
|
| 476 |
+
def create(self, method: str, url: str) -> None:
|
| 477 |
+
try:
|
| 478 |
+
req = http.Request.make(method.upper(), url)
|
| 479 |
+
except ValueError as e:
|
| 480 |
+
raise exceptions.CommandError("Invalid URL: %s" % e)
|
| 481 |
+
|
| 482 |
+
c = connection.Client(
|
| 483 |
+
peername=("", 0),
|
| 484 |
+
sockname=("", 0),
|
| 485 |
+
timestamp_start=req.timestamp_start - 0.0001,
|
| 486 |
+
)
|
| 487 |
+
s = connection.Server(address=(req.host, req.port))
|
| 488 |
+
|
| 489 |
+
f = http.HTTPFlow(c, s)
|
| 490 |
+
f.request = req
|
| 491 |
+
f.request.headers["Host"] = req.host
|
| 492 |
+
self.add([f])
|
| 493 |
+
|
| 494 |
+
@command.command("view.flows.load")
|
| 495 |
+
def load_file(self, path: mitmproxy.types.Path) -> None:
|
| 496 |
+
"""
|
| 497 |
+
Load flows into the view, without processing them with addons.
|
| 498 |
+
"""
|
| 499 |
+
try:
|
| 500 |
+
with open(path, "rb") as f:
|
| 501 |
+
for i in io.FlowReader(f).stream():
|
| 502 |
+
# Do this to get a new ID, so we can load the same file N times and
|
| 503 |
+
# get new flows each time. It would be more efficient to just have a
|
| 504 |
+
# .newid() method or something.
|
| 505 |
+
self.add([i.copy()])
|
| 506 |
+
except OSError as e:
|
| 507 |
+
logging.error(e.strerror)
|
| 508 |
+
except exceptions.FlowReadException as e:
|
| 509 |
+
logging.error(str(e))
|
| 510 |
+
|
| 511 |
+
def add(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
|
| 512 |
+
"""
|
| 513 |
+
Adds a flow to the state. If the flow already exists, it is
|
| 514 |
+
ignored.
|
| 515 |
+
"""
|
| 516 |
+
for f in flows:
|
| 517 |
+
if f.id not in self._store:
|
| 518 |
+
self._store[f.id] = f
|
| 519 |
+
if self.filter(f):
|
| 520 |
+
self._base_add(f)
|
| 521 |
+
if self.focus_follow:
|
| 522 |
+
self.focus.flow = f
|
| 523 |
+
self.sig_view_add.send(flow=f)
|
| 524 |
+
|
| 525 |
+
def get_by_id(self, flow_id: str) -> mitmproxy.flow.Flow | None:
|
| 526 |
+
"""
|
| 527 |
+
Get flow with the given id from the store.
|
| 528 |
+
Returns None if the flow is not found.
|
| 529 |
+
"""
|
| 530 |
+
return self._store.get(flow_id)
|
| 531 |
+
|
| 532 |
+
# View Properties
|
| 533 |
+
@command.command("view.properties.length")
|
| 534 |
+
def get_length(self) -> int:
|
| 535 |
+
"""
|
| 536 |
+
Returns view length.
|
| 537 |
+
"""
|
| 538 |
+
return len(self)
|
| 539 |
+
|
| 540 |
+
@command.command("view.properties.marked")
|
| 541 |
+
def get_marked(self) -> bool:
|
| 542 |
+
"""
|
| 543 |
+
Returns true if view is in marked mode.
|
| 544 |
+
"""
|
| 545 |
+
return self.show_marked
|
| 546 |
+
|
| 547 |
+
@command.command("view.properties.marked.toggle")
|
| 548 |
+
def toggle_marked(self) -> None:
|
| 549 |
+
"""
|
| 550 |
+
Toggle whether to show marked views only.
|
| 551 |
+
"""
|
| 552 |
+
self.show_marked = not self.show_marked
|
| 553 |
+
self._refilter()
|
| 554 |
+
|
| 555 |
+
@command.command("view.properties.inbounds")
|
| 556 |
+
def inbounds(self, index: int) -> bool:
|
| 557 |
+
"""
|
| 558 |
+
Is this 0 <= index < len(self)?
|
| 559 |
+
"""
|
| 560 |
+
return 0 <= index < len(self)
|
| 561 |
+
|
| 562 |
+
# Event handlers
|
| 563 |
+
def configure(self, updated):
|
| 564 |
+
if "view_filter" in updated:
|
| 565 |
+
filt = None
|
| 566 |
+
if ctx.options.view_filter:
|
| 567 |
+
try:
|
| 568 |
+
filt = flowfilter.parse(ctx.options.view_filter)
|
| 569 |
+
except ValueError as e:
|
| 570 |
+
raise exceptions.OptionsError(str(e)) from e
|
| 571 |
+
self.set_filter(filt)
|
| 572 |
+
if "view_order" in updated:
|
| 573 |
+
if ctx.options.view_order not in self.orders:
|
| 574 |
+
raise exceptions.OptionsError(
|
| 575 |
+
"Unknown flow order: %s" % ctx.options.view_order
|
| 576 |
+
)
|
| 577 |
+
self.set_order(ctx.options.view_order)
|
| 578 |
+
if "view_order_reversed" in updated:
|
| 579 |
+
self.set_reversed(ctx.options.view_order_reversed)
|
| 580 |
+
if "console_focus_follow" in updated:
|
| 581 |
+
self.focus_follow = ctx.options.console_focus_follow
|
| 582 |
+
|
| 583 |
+
def requestheaders(self, f):
|
| 584 |
+
self.add([f])
|
| 585 |
+
|
| 586 |
+
def error(self, f):
|
| 587 |
+
self.update([f])
|
| 588 |
+
|
| 589 |
+
def response(self, f):
|
| 590 |
+
self.update([f])
|
| 591 |
+
|
| 592 |
+
def intercept(self, f):
|
| 593 |
+
self.update([f])
|
| 594 |
+
|
| 595 |
+
def resume(self, f):
|
| 596 |
+
self.update([f])
|
| 597 |
+
|
| 598 |
+
def kill(self, f):
|
| 599 |
+
self.update([f])
|
| 600 |
+
|
| 601 |
+
def tcp_start(self, f):
|
| 602 |
+
self.add([f])
|
| 603 |
+
|
| 604 |
+
def tcp_message(self, f):
|
| 605 |
+
self.update([f])
|
| 606 |
+
|
| 607 |
+
def tcp_error(self, f):
|
| 608 |
+
self.update([f])
|
| 609 |
+
|
| 610 |
+
def tcp_end(self, f):
|
| 611 |
+
self.update([f])
|
| 612 |
+
|
| 613 |
+
def udp_start(self, f):
|
| 614 |
+
self.add([f])
|
| 615 |
+
|
| 616 |
+
def udp_message(self, f):
|
| 617 |
+
self.update([f])
|
| 618 |
+
|
| 619 |
+
def udp_error(self, f):
|
| 620 |
+
self.update([f])
|
| 621 |
+
|
| 622 |
+
def udp_end(self, f):
|
| 623 |
+
self.update([f])
|
| 624 |
+
|
| 625 |
+
def dns_request(self, f):
|
| 626 |
+
self.add([f])
|
| 627 |
+
|
| 628 |
+
def dns_response(self, f):
|
| 629 |
+
self.update([f])
|
| 630 |
+
|
| 631 |
+
def dns_error(self, f):
|
| 632 |
+
self.update([f])
|
| 633 |
+
|
| 634 |
+
def update(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
|
| 635 |
+
"""
|
| 636 |
+
Updates a list of flows. If flow is not in the state, it's ignored.
|
| 637 |
+
"""
|
| 638 |
+
for f in flows:
|
| 639 |
+
if f.id in self._store:
|
| 640 |
+
if self.filter(f):
|
| 641 |
+
if f not in self._view:
|
| 642 |
+
self._base_add(f)
|
| 643 |
+
if self.focus_follow:
|
| 644 |
+
self.focus.flow = f
|
| 645 |
+
self.sig_view_add.send(flow=f)
|
| 646 |
+
else:
|
| 647 |
+
# This is a tad complicated. The sortedcontainers
|
| 648 |
+
# implementation assumes that the order key is stable. If
|
| 649 |
+
# it changes mid-way Very Bad Things happen. We detect when
|
| 650 |
+
# this happens, and re-fresh the item.
|
| 651 |
+
self.order_key.refresh(f)
|
| 652 |
+
self.sig_view_update.send(flow=f)
|
| 653 |
+
else:
|
| 654 |
+
try:
|
| 655 |
+
idx = self._view.index(f)
|
| 656 |
+
except ValueError:
|
| 657 |
+
pass # The value was not in the view
|
| 658 |
+
else:
|
| 659 |
+
self._view.remove(f)
|
| 660 |
+
self.sig_view_remove.send(flow=f, index=idx)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
class Focus:
|
| 664 |
+
"""
|
| 665 |
+
Tracks a focus element within a View.
|
| 666 |
+
"""
|
| 667 |
+
|
| 668 |
+
def __init__(self, v: View) -> None:
|
| 669 |
+
self.view = v
|
| 670 |
+
self._flow: mitmproxy.flow.Flow | None = None
|
| 671 |
+
self.sig_change = signals.SyncSignal(lambda: None)
|
| 672 |
+
if len(self.view):
|
| 673 |
+
self.flow = self.view[0]
|
| 674 |
+
v.sig_view_add.connect(self._sig_view_add)
|
| 675 |
+
v.sig_view_remove.connect(self._sig_view_remove)
|
| 676 |
+
v.sig_view_refresh.connect(self._sig_view_refresh)
|
| 677 |
+
|
| 678 |
+
@property
|
| 679 |
+
def flow(self) -> mitmproxy.flow.Flow | None:
|
| 680 |
+
return self._flow
|
| 681 |
+
|
| 682 |
+
@flow.setter
|
| 683 |
+
def flow(self, f: mitmproxy.flow.Flow | None):
|
| 684 |
+
if f is not None and f not in self.view:
|
| 685 |
+
raise ValueError("Attempt to set focus to flow not in view")
|
| 686 |
+
self._flow = f
|
| 687 |
+
self.sig_change.send()
|
| 688 |
+
|
| 689 |
+
@property
|
| 690 |
+
def index(self) -> int | None:
|
| 691 |
+
if self.flow:
|
| 692 |
+
return self.view.index(self.flow)
|
| 693 |
+
return None
|
| 694 |
+
|
| 695 |
+
@index.setter
|
| 696 |
+
def index(self, idx):
|
| 697 |
+
if idx < 0 or idx > len(self.view) - 1:
|
| 698 |
+
raise ValueError("Index out of view bounds")
|
| 699 |
+
self.flow = self.view[idx]
|
| 700 |
+
|
| 701 |
+
def _nearest(self, f, v):
|
| 702 |
+
return min(v._bisect(f), len(v) - 1)
|
| 703 |
+
|
| 704 |
+
def _sig_view_remove(self, flow, index):
|
| 705 |
+
if len(self.view) == 0:
|
| 706 |
+
self.flow = None
|
| 707 |
+
elif flow is self.flow:
|
| 708 |
+
self.index = min(index, len(self.view) - 1)
|
| 709 |
+
|
| 710 |
+
def _sig_view_refresh(self):
|
| 711 |
+
if len(self.view) == 0:
|
| 712 |
+
self.flow = None
|
| 713 |
+
elif self.flow is None:
|
| 714 |
+
self.flow = self.view[0]
|
| 715 |
+
elif self.flow not in self.view:
|
| 716 |
+
self.flow = self.view[self._nearest(self.flow, self.view)]
|
| 717 |
+
|
| 718 |
+
def _sig_view_add(self, flow):
|
| 719 |
+
# We only have to act if we don't have a focus element
|
| 720 |
+
if not self.flow:
|
| 721 |
+
self.flow = flow
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
class Settings(collections.abc.Mapping):
|
| 725 |
+
def __init__(self, view: View) -> None:
|
| 726 |
+
self.view = view
|
| 727 |
+
self._values: MutableMapping[str, dict] = {}
|
| 728 |
+
view.sig_store_remove.connect(self._sig_store_remove)
|
| 729 |
+
view.sig_store_refresh.connect(self._sig_store_refresh)
|
| 730 |
+
|
| 731 |
+
def __iter__(self) -> Iterator:
|
| 732 |
+
return iter(self._values)
|
| 733 |
+
|
| 734 |
+
def __len__(self) -> int:
|
| 735 |
+
return len(self._values)
|
| 736 |
+
|
| 737 |
+
def __getitem__(self, f: mitmproxy.flow.Flow) -> dict:
|
| 738 |
+
if f.id not in self.view._store:
|
| 739 |
+
raise KeyError
|
| 740 |
+
return self._values.setdefault(f.id, {})
|
| 741 |
+
|
| 742 |
+
def _sig_store_remove(self, flow):
|
| 743 |
+
if flow.id in self._values:
|
| 744 |
+
del self._values[flow.id]
|
| 745 |
+
|
| 746 |
+
def _sig_store_refresh(self):
|
| 747 |
+
for fid in list(self._values.keys()):
|
| 748 |
+
if fid not in self.view._store:
|
| 749 |
+
del self._values[fid]
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_api.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import typing
|
| 5 |
+
from abc import abstractmethod
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Literal
|
| 9 |
+
|
| 10 |
+
from mitmproxy import http
|
| 11 |
+
from mitmproxy import tcp
|
| 12 |
+
from mitmproxy import udp
|
| 13 |
+
from mitmproxy.dns import DNSMessage
|
| 14 |
+
from mitmproxy.flow import Flow
|
| 15 |
+
from mitmproxy.websocket import WebSocketMessage
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
type SyntaxHighlight = Literal["css", "javascript", "xml", "yaml", "none", "error"]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@typing.runtime_checkable
|
| 24 |
+
class Contentview(typing.Protocol):
|
| 25 |
+
"""
|
| 26 |
+
Base class for all contentviews.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def name(self) -> str:
|
| 31 |
+
"""
|
| 32 |
+
The name of this contentview, e.g. "XML/HTML".
|
| 33 |
+
Inferred from the class name by default.
|
| 34 |
+
"""
|
| 35 |
+
return type(self).__name__.removesuffix("Contentview")
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def syntax_highlight(self) -> SyntaxHighlight:
|
| 39 |
+
"""Optional syntax highlighting that should be applied to the prettified output."""
|
| 40 |
+
return "none"
|
| 41 |
+
|
| 42 |
+
@abstractmethod
|
| 43 |
+
def prettify(
|
| 44 |
+
self,
|
| 45 |
+
data: bytes,
|
| 46 |
+
metadata: Metadata,
|
| 47 |
+
) -> str:
|
| 48 |
+
"""
|
| 49 |
+
Transform raw data into human-readable output.
|
| 50 |
+
May raise an exception (e.g. `ValueError`) if data cannot be prettified.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def render_priority(
|
| 54 |
+
self,
|
| 55 |
+
data: bytes,
|
| 56 |
+
metadata: Metadata,
|
| 57 |
+
) -> float:
|
| 58 |
+
"""
|
| 59 |
+
Return the priority of this view for rendering `data`.
|
| 60 |
+
If no particular view is chosen by the user, the view with the highest priority is selected.
|
| 61 |
+
If this view does not support the given data, return a float < 0.
|
| 62 |
+
"""
|
| 63 |
+
return 0
|
| 64 |
+
|
| 65 |
+
def __lt__(self, other):
|
| 66 |
+
return self.name.__lt__(other.name)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@typing.runtime_checkable
|
| 70 |
+
class InteractiveContentview(Contentview, typing.Protocol):
|
| 71 |
+
"""A contentview that prettifies raw data and allows for interactive editing."""
|
| 72 |
+
|
| 73 |
+
@abstractmethod
|
| 74 |
+
def reencode(
|
| 75 |
+
self,
|
| 76 |
+
prettified: str,
|
| 77 |
+
metadata: Metadata,
|
| 78 |
+
) -> bytes:
|
| 79 |
+
"""
|
| 80 |
+
Reencode the given (modified) `prettified` output into the original data format.
|
| 81 |
+
May raise an exception (e.g. `ValueError`) if reencoding failed.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@dataclass
|
| 86 |
+
class Metadata:
|
| 87 |
+
"""
|
| 88 |
+
Metadata about the data that is being prettified.
|
| 89 |
+
|
| 90 |
+
Do not rely on any given attribute to be present.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
flow: Flow | None = None
|
| 94 |
+
"""The flow that the data belongs to, if any."""
|
| 95 |
+
|
| 96 |
+
content_type: str | None = None
|
| 97 |
+
"""The HTTP content type of the data, if any."""
|
| 98 |
+
http_message: http.Message | None = None
|
| 99 |
+
"""The HTTP message that the data belongs to, if any."""
|
| 100 |
+
tcp_message: tcp.TCPMessage | None = None
|
| 101 |
+
"""The TCP message that the data belongs to, if any."""
|
| 102 |
+
udp_message: udp.UDPMessage | None = None
|
| 103 |
+
"""The UDP message that the data belongs to, if any."""
|
| 104 |
+
websocket_message: WebSocketMessage | None = None
|
| 105 |
+
"""The websocket message that the data belongs to, if any."""
|
| 106 |
+
dns_message: DNSMessage | None = None
|
| 107 |
+
"""The DNS message that the data belongs to, if any."""
|
| 108 |
+
|
| 109 |
+
protobuf_definitions: Path | None = None
|
| 110 |
+
"""Path to a .proto file that's used to resolve Protobuf field names."""
|
| 111 |
+
|
| 112 |
+
original_data: bytes | None = None
|
| 113 |
+
"""When reencoding: The original data that was prettified."""
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
Metadata.__init__.__doc__ = "@private"
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_compat.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import typing
|
| 5 |
+
from typing import Iterator
|
| 6 |
+
|
| 7 |
+
from mitmproxy import contentviews
|
| 8 |
+
from mitmproxy.contentviews import SyntaxHighlight
|
| 9 |
+
from mitmproxy.contentviews._api import Contentview
|
| 10 |
+
from mitmproxy.contentviews._api import Metadata
|
| 11 |
+
from mitmproxy.utils.strutils import always_str
|
| 12 |
+
|
| 13 |
+
if sys.version_info < (3, 13): # pragma: no cover
|
| 14 |
+
from typing_extensions import deprecated
|
| 15 |
+
else:
|
| 16 |
+
from warnings import deprecated
|
| 17 |
+
|
| 18 |
+
if typing.TYPE_CHECKING:
|
| 19 |
+
from mitmproxy.contentviews.base import TViewLine
|
| 20 |
+
from mitmproxy.contentviews.base import View
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class LegacyContentview(Contentview):
|
| 24 |
+
@property
|
| 25 |
+
def name(self) -> str:
|
| 26 |
+
return self.contentview.name
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def syntax_highlight(self) -> SyntaxHighlight:
|
| 30 |
+
return getattr(self.contentview, "syntax_highlight", "none")
|
| 31 |
+
|
| 32 |
+
def render_priority(
|
| 33 |
+
self,
|
| 34 |
+
data: bytes,
|
| 35 |
+
metadata: Metadata,
|
| 36 |
+
) -> float:
|
| 37 |
+
return (
|
| 38 |
+
self.contentview.render_priority(
|
| 39 |
+
data=data,
|
| 40 |
+
content_type=metadata.content_type,
|
| 41 |
+
flow=metadata.flow,
|
| 42 |
+
http_message=metadata.http_message,
|
| 43 |
+
)
|
| 44 |
+
or 0.0
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
def prettify(self, data: bytes, metadata: Metadata) -> str:
|
| 48 |
+
lines: Iterator[TViewLine]
|
| 49 |
+
desc_, lines = self.contentview(
|
| 50 |
+
data,
|
| 51 |
+
content_type=metadata.content_type,
|
| 52 |
+
flow=metadata.flow,
|
| 53 |
+
http_message=metadata.http_message,
|
| 54 |
+
)
|
| 55 |
+
return "\n".join(
|
| 56 |
+
"".join(always_str(text, "utf8", "backslashescape") for tag, text in line)
|
| 57 |
+
for line in lines
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def __init__(self, contentview: View):
|
| 61 |
+
self.contentview = contentview
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@deprecated("Use `mitmproxy.contentviews.registry` instead.")
|
| 65 |
+
def get(name: str) -> Contentview | None:
|
| 66 |
+
try:
|
| 67 |
+
return contentviews.registry[name.lower()]
|
| 68 |
+
except KeyError:
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@deprecated("Use `mitmproxy.contentviews.Contentview` instead.")
|
| 73 |
+
def remove(view: View):
|
| 74 |
+
pass
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_registry.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import typing
|
| 5 |
+
from collections.abc import Mapping
|
| 6 |
+
|
| 7 |
+
from ..utils import signals
|
| 8 |
+
from ._api import Contentview
|
| 9 |
+
from ._api import Metadata
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _on_change(view: Contentview) -> None: ...
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ContentviewRegistry(Mapping[str, Contentview]):
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self._by_name: dict[str, Contentview] = {}
|
| 20 |
+
self.on_change = signals.SyncSignal(_on_change)
|
| 21 |
+
|
| 22 |
+
def register(self, instance: Contentview | type[Contentview]) -> None:
|
| 23 |
+
if isinstance(instance, type):
|
| 24 |
+
instance = instance()
|
| 25 |
+
name = instance.name.lower()
|
| 26 |
+
if name in self._by_name:
|
| 27 |
+
logger.info(f"Replacing existing {name} contentview.")
|
| 28 |
+
self._by_name[name] = instance
|
| 29 |
+
self.on_change.send(instance)
|
| 30 |
+
|
| 31 |
+
def available_views(self) -> list[str]:
|
| 32 |
+
return ["auto", *sorted(self._by_name.keys())]
|
| 33 |
+
|
| 34 |
+
def get_view(
|
| 35 |
+
self, data: bytes, metadata: Metadata, view_name: str = "auto"
|
| 36 |
+
) -> Contentview:
|
| 37 |
+
"""
|
| 38 |
+
Get the best contentview for the given data and metadata.
|
| 39 |
+
|
| 40 |
+
If `view_name` is "auto" or the provided view not found,
|
| 41 |
+
the best matching contentview based on `render_priority` will be returned.
|
| 42 |
+
"""
|
| 43 |
+
if view_name != "auto":
|
| 44 |
+
try:
|
| 45 |
+
return self[view_name.lower()]
|
| 46 |
+
except KeyError:
|
| 47 |
+
logger.warning(
|
| 48 |
+
f"Unknown contentview {view_name!r}, selecting best match instead."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
max_prio: tuple[float, Contentview] | None = None
|
| 52 |
+
for name, view in self._by_name.items():
|
| 53 |
+
try:
|
| 54 |
+
priority = view.render_priority(data, metadata)
|
| 55 |
+
assert isinstance(priority, (int, float)), (
|
| 56 |
+
f"render_priority for {view.name} did not return a number."
|
| 57 |
+
)
|
| 58 |
+
except Exception:
|
| 59 |
+
logger.exception(f"Error in {view.name}.render_priority")
|
| 60 |
+
else:
|
| 61 |
+
if max_prio is None or max_prio[0] < priority:
|
| 62 |
+
max_prio = (priority, view)
|
| 63 |
+
assert max_prio, "At least one view needs to have a working `render_priority`."
|
| 64 |
+
return max_prio[1]
|
| 65 |
+
|
| 66 |
+
def __iter__(self) -> typing.Iterator[str]:
|
| 67 |
+
return iter(self._by_name)
|
| 68 |
+
|
| 69 |
+
def __getitem__(self, item: str) -> Contentview:
|
| 70 |
+
return self._by_name[item.lower()]
|
| 71 |
+
|
| 72 |
+
def __len__(self):
|
| 73 |
+
return len(self._by_name)
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_utils.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import typing
|
| 3 |
+
from collections.abc import Iterable
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from ruamel.yaml import YAML
|
| 8 |
+
|
| 9 |
+
from .. import ctx
|
| 10 |
+
from .. import http
|
| 11 |
+
from ..dns import DNSMessage
|
| 12 |
+
from ..flow import Flow
|
| 13 |
+
from ..tcp import TCPMessage
|
| 14 |
+
from ..udp import UDPMessage
|
| 15 |
+
from ..utils import strutils
|
| 16 |
+
from ..websocket import WebSocketMessage
|
| 17 |
+
from ._api import Metadata
|
| 18 |
+
|
| 19 |
+
type ContentviewMessage = (
|
| 20 |
+
http.Message | TCPMessage | UDPMessage | WebSocketMessage | DNSMessage
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def make_metadata(
|
| 25 |
+
message: ContentviewMessage,
|
| 26 |
+
flow: Flow,
|
| 27 |
+
) -> Metadata:
|
| 28 |
+
metadata = Metadata(
|
| 29 |
+
flow=flow,
|
| 30 |
+
protobuf_definitions=Path(ctx.options.protobuf_definitions).expanduser()
|
| 31 |
+
if ctx.options.protobuf_definitions
|
| 32 |
+
else None,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
match message:
|
| 36 |
+
case http.Message():
|
| 37 |
+
metadata.http_message = message
|
| 38 |
+
if ctype := message.headers.get("content-type"):
|
| 39 |
+
if ct := http.parse_content_type(ctype):
|
| 40 |
+
metadata.content_type = f"{ct[0]}/{ct[1]}"
|
| 41 |
+
case TCPMessage():
|
| 42 |
+
metadata.tcp_message = message
|
| 43 |
+
case UDPMessage():
|
| 44 |
+
metadata.udp_message = message
|
| 45 |
+
case WebSocketMessage():
|
| 46 |
+
metadata.websocket_message = message
|
| 47 |
+
case DNSMessage():
|
| 48 |
+
metadata.dns_message = message
|
| 49 |
+
case other: # pragma: no cover
|
| 50 |
+
typing.assert_never(other)
|
| 51 |
+
|
| 52 |
+
return metadata
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_data(
|
| 56 |
+
message: ContentviewMessage,
|
| 57 |
+
) -> tuple[bytes | None, str]:
|
| 58 |
+
content: bytes | None
|
| 59 |
+
try:
|
| 60 |
+
content = message.content
|
| 61 |
+
except ValueError:
|
| 62 |
+
assert isinstance(message, http.Message)
|
| 63 |
+
content = message.raw_content
|
| 64 |
+
enc = "[cannot decode]"
|
| 65 |
+
else:
|
| 66 |
+
if isinstance(message, http.Message) and content != message.raw_content:
|
| 67 |
+
enc = "[decoded {}]".format(message.headers.get("content-encoding"))
|
| 68 |
+
else:
|
| 69 |
+
enc = ""
|
| 70 |
+
|
| 71 |
+
return content, enc
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def yaml_dumps(d: Any) -> str:
|
| 75 |
+
if not d:
|
| 76 |
+
return ""
|
| 77 |
+
out = io.StringIO()
|
| 78 |
+
YAML(typ="rt", pure=True).dump(d, out)
|
| 79 |
+
return out.getvalue()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def yaml_loads(yaml: str) -> Any:
|
| 83 |
+
return YAML(typ="safe", pure=True).load(yaml)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def merge_repeated_keys(items: Iterable[tuple[str, str]]) -> dict[str, str | list[str]]:
|
| 87 |
+
"""
|
| 88 |
+
Helper function that takes a list of pairs and merges repeated keys.
|
| 89 |
+
"""
|
| 90 |
+
ret: dict[str, str | list[str]] = {}
|
| 91 |
+
for key, value in items:
|
| 92 |
+
if existing := ret.get(key):
|
| 93 |
+
if isinstance(existing, list):
|
| 94 |
+
existing.append(value)
|
| 95 |
+
else:
|
| 96 |
+
ret[key] = [existing, value]
|
| 97 |
+
else:
|
| 98 |
+
ret[key] = value
|
| 99 |
+
return ret
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def byte_pairs_to_str_pairs(
|
| 103 |
+
items: Iterable[tuple[bytes, bytes]],
|
| 104 |
+
) -> Iterable[tuple[str, str]]:
|
| 105 |
+
for key, value in items:
|
| 106 |
+
yield (strutils.bytes_to_escaped_str(key), strutils.bytes_to_escaped_str(value))
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_css.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import time
|
| 3 |
+
|
| 4 |
+
from mitmproxy.contentviews._api import Contentview
|
| 5 |
+
from mitmproxy.contentviews._api import Metadata
|
| 6 |
+
from mitmproxy.utils import strutils
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
A custom CSS prettifier. Compared to other prettifiers, its main features are:
|
| 10 |
+
|
| 11 |
+
- Implemented in pure Python.
|
| 12 |
+
- Modifies whitespace only.
|
| 13 |
+
- Works with any input.
|
| 14 |
+
- Considerably faster than e.g. cssutils.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
CSS_SPECIAL_AREAS = (
|
| 18 |
+
"'" + strutils.SINGLELINE_CONTENT + strutils.NO_ESCAPE + "'",
|
| 19 |
+
'"' + strutils.SINGLELINE_CONTENT + strutils.NO_ESCAPE + '"',
|
| 20 |
+
r"/\*" + strutils.MULTILINE_CONTENT + r"\*/",
|
| 21 |
+
"//" + strutils.SINGLELINE_CONTENT + "$",
|
| 22 |
+
)
|
| 23 |
+
CSS_SPECIAL_CHARS = "{};:"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def beautify(data: str, indent: str = " "):
|
| 27 |
+
"""Beautify a string containing CSS code"""
|
| 28 |
+
data = strutils.escape_special_areas(
|
| 29 |
+
data.strip(),
|
| 30 |
+
CSS_SPECIAL_AREAS,
|
| 31 |
+
CSS_SPECIAL_CHARS,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Add newlines
|
| 35 |
+
data = re.sub(r"\s*;\s*", ";\n", data)
|
| 36 |
+
data = re.sub(r"\s*{\s*", " {\n", data)
|
| 37 |
+
data = re.sub(r"\s*}\s*", "\n}\n\n", data)
|
| 38 |
+
|
| 39 |
+
# Fix incorrect ":" placement
|
| 40 |
+
data = re.sub(r"\s*:\s*(?=[^{]+})", ": ", data)
|
| 41 |
+
# Fix no space after ","
|
| 42 |
+
data = re.sub(r"\s*,\s*", ", ", data)
|
| 43 |
+
|
| 44 |
+
# indent
|
| 45 |
+
data = re.sub("\n[ \t]+", "\n", data)
|
| 46 |
+
data = re.sub("\n(?![}\n])(?=[^{]*})", "\n" + indent, data)
|
| 47 |
+
|
| 48 |
+
data = strutils.unescape_special_areas(data)
|
| 49 |
+
return data.rstrip("\n") + "\n"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ViewCSS(Contentview):
|
| 53 |
+
syntax_highlight = "css"
|
| 54 |
+
|
| 55 |
+
def prettify(self, data: bytes, metadata: Metadata) -> str:
|
| 56 |
+
data_str = data.decode("utf8", "surrogateescape")
|
| 57 |
+
return beautify(data_str)
|
| 58 |
+
|
| 59 |
+
def render_priority(
|
| 60 |
+
self,
|
| 61 |
+
data: bytes,
|
| 62 |
+
metadata: Metadata,
|
| 63 |
+
) -> float:
|
| 64 |
+
return float(bool(data) and metadata.content_type == "text/css")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
css = ViewCSS()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__": # pragma: no cover
|
| 71 |
+
with open("../tools/web/static/vendor.css") as f:
|
| 72 |
+
data = f.read()
|
| 73 |
+
|
| 74 |
+
t = time.time()
|
| 75 |
+
x = beautify(data)
|
| 76 |
+
print(f"Beautifying vendor.css took {time.time() - t:.2}s")
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_dns.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mitmproxy.contentviews._api import InteractiveContentview
|
| 2 |
+
from mitmproxy.contentviews._api import Metadata
|
| 3 |
+
from mitmproxy.contentviews._utils import yaml_dumps
|
| 4 |
+
from mitmproxy.contentviews._utils import yaml_loads
|
| 5 |
+
from mitmproxy.dns import DNSMessage as DNSMessage
|
| 6 |
+
from mitmproxy.proxy.layers.dns import pack_message
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _is_dns_tcp(metadata: Metadata) -> bool:
|
| 10 |
+
return bool(metadata.tcp_message or metadata.http_message)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class DNSContentview(InteractiveContentview):
|
| 14 |
+
syntax_highlight = "yaml"
|
| 15 |
+
|
| 16 |
+
def prettify(
|
| 17 |
+
self,
|
| 18 |
+
data: bytes,
|
| 19 |
+
metadata: Metadata,
|
| 20 |
+
) -> str:
|
| 21 |
+
if _is_dns_tcp(metadata):
|
| 22 |
+
data = data[2:] # hack: cut off length label and hope for the best
|
| 23 |
+
message = DNSMessage.unpack(data).to_json()
|
| 24 |
+
del message["status_code"]
|
| 25 |
+
message.pop("timestamp", None)
|
| 26 |
+
return yaml_dumps(message)
|
| 27 |
+
|
| 28 |
+
def reencode(
|
| 29 |
+
self,
|
| 30 |
+
prettified: str,
|
| 31 |
+
metadata: Metadata,
|
| 32 |
+
) -> bytes:
|
| 33 |
+
data = yaml_loads(prettified)
|
| 34 |
+
message = DNSMessage.from_json(data)
|
| 35 |
+
return pack_message(message, "tcp" if _is_dns_tcp(metadata) else "udp")
|
| 36 |
+
|
| 37 |
+
def render_priority(
|
| 38 |
+
self,
|
| 39 |
+
data: bytes,
|
| 40 |
+
metadata: Metadata,
|
| 41 |
+
) -> float:
|
| 42 |
+
return float(
|
| 43 |
+
metadata.content_type == "application/dns-message"
|
| 44 |
+
or bool(
|
| 45 |
+
metadata.flow
|
| 46 |
+
and metadata.flow.server_conn
|
| 47 |
+
and metadata.flow.server_conn.address
|
| 48 |
+
and metadata.flow.server_conn.address[1] in (53, 5353)
|
| 49 |
+
)
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
dns = DNSContentview()
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_graphql.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from mitmproxy.contentviews._api import Contentview
|
| 5 |
+
from mitmproxy.contentviews._api import Metadata
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def format_graphql(data):
|
| 9 |
+
query = data["query"]
|
| 10 |
+
header_data = data.copy()
|
| 11 |
+
header_data["query"] = "..."
|
| 12 |
+
return """{header}
|
| 13 |
+
---
|
| 14 |
+
{query}
|
| 15 |
+
""".format(header=json.dumps(header_data, indent=2), query=query)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def format_query_list(data: list[Any]):
|
| 19 |
+
num_queries = len(data) - 1
|
| 20 |
+
result = ""
|
| 21 |
+
for i, op in enumerate(data):
|
| 22 |
+
result += f"--- {i}/{num_queries}\n"
|
| 23 |
+
result += format_graphql(op)
|
| 24 |
+
return result
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def is_graphql_query(data):
|
| 28 |
+
return isinstance(data, dict) and "query" in data and "\n" in data["query"]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def is_graphql_batch_query(data):
|
| 32 |
+
return (
|
| 33 |
+
isinstance(data, list)
|
| 34 |
+
and len(data) > 0
|
| 35 |
+
and isinstance(data[0], dict)
|
| 36 |
+
and "query" in data[0]
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class GraphQLContentview(Contentview):
|
| 41 |
+
def prettify(
|
| 42 |
+
self,
|
| 43 |
+
data: bytes,
|
| 44 |
+
metadata: Metadata,
|
| 45 |
+
) -> str:
|
| 46 |
+
gql = json.loads(data)
|
| 47 |
+
if is_graphql_query(gql):
|
| 48 |
+
return format_graphql(gql)
|
| 49 |
+
elif is_graphql_batch_query(gql):
|
| 50 |
+
return format_query_list(gql)
|
| 51 |
+
else:
|
| 52 |
+
raise ValueError("Not a GraphQL message.")
|
| 53 |
+
|
| 54 |
+
def render_priority(
|
| 55 |
+
self,
|
| 56 |
+
data: bytes,
|
| 57 |
+
metadata: Metadata,
|
| 58 |
+
) -> float:
|
| 59 |
+
if metadata.content_type != "application/json" or not data:
|
| 60 |
+
return 0
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
data = json.loads(data)
|
| 64 |
+
if is_graphql_query(data) or is_graphql_batch_query(data):
|
| 65 |
+
return 2
|
| 66 |
+
except ValueError:
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
return 0
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
graphql = GraphQLContentview()
|
python/user_packages/Python313/site-packages/mitmproxy/contentviews/_view_http3.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from dataclasses import field
|
| 4 |
+
|
| 5 |
+
import pylsqpack
|
| 6 |
+
from aioquic.buffer import Buffer
|
| 7 |
+
from aioquic.buffer import BufferReadError
|
| 8 |
+
from aioquic.h3.connection import parse_settings
|
| 9 |
+
from aioquic.h3.connection import Setting
|
| 10 |
+
|
| 11 |
+
from ..proxy.layers.http import is_h3_alpn
|
| 12 |
+
from mitmproxy import tcp
|
| 13 |
+
from mitmproxy.contentviews._api import Contentview
|
| 14 |
+
from mitmproxy.contentviews._api import Metadata
|
| 15 |
+
from mitmproxy_rs.contentviews import hex_dump
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass(frozen=True)
|
| 19 |
+
class Frame:
|
| 20 |
+
"""Representation of an HTTP/3 frame."""
|
| 21 |
+
|
| 22 |
+
type: int
|
| 23 |
+
data: bytes
|
| 24 |
+
|
| 25 |
+
def pretty(self) -> str:
|
| 26 |
+
frame_name = f"0x{self.type:x} Frame"
|
| 27 |
+
if self.type == 0:
|
| 28 |
+
frame_name = "DATA Frame"
|
| 29 |
+
elif self.type == 1:
|
| 30 |
+
try:
|
| 31 |
+
hdrs = pylsqpack.Decoder(4096, 16).feed_header(0, self.data)[1]
|
| 32 |
+
return f"HEADERS Frame\n" + "\n".join(
|
| 33 |
+
f"{k.decode(errors='backslashreplace')}: {v.decode(errors='backslashreplace')}"
|
| 34 |
+
for k, v in hdrs
|
| 35 |
+
)
|
| 36 |
+
except Exception as e:
|
| 37 |
+
frame_name = f"HEADERS Frame (error: {e})"
|
| 38 |
+
elif self.type == 4:
|
| 39 |
+
settings = []
|
| 40 |
+
try:
|
| 41 |
+
s = parse_settings(self.data)
|
| 42 |
+
except Exception as e:
|
| 43 |
+
frame_name = f"SETTINGS Frame (error: {e})"
|
| 44 |
+
else:
|
| 45 |
+
for k, v in s.items():
|
| 46 |
+
try:
|
| 47 |
+
key = Setting(k).name
|
| 48 |
+
except ValueError:
|
| 49 |
+
key = f"0x{k:x}"
|
| 50 |
+
settings.append(f"{key}: 0x{v:x}")
|
| 51 |
+
return "SETTINGS Frame\n" + "\n".join(settings)
|
| 52 |
+
return f"{frame_name}\n" + hex_dump.prettify(self.data, Metadata())
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass(frozen=True)
|
| 56 |
+
class StreamType:
|
| 57 |
+
"""Representation of an HTTP/3 stream types."""
|
| 58 |
+
|
| 59 |
+
type: int
|
| 60 |
+
|
| 61 |
+
def pretty(self) -> str:
|
| 62 |
+
stream_type = {
|
| 63 |
+
0x00: "Control Stream",
|
| 64 |
+
0x01: "Push Stream",
|
| 65 |
+
0x02: "QPACK Encoder Stream",
|
| 66 |
+
0x03: "QPACK Decoder Stream",
|
| 67 |
+
}.get(self.type, f"0x{self.type:x} Stream")
|
| 68 |
+
return stream_type
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass
|
| 72 |
+
class ConnectionState:
|
| 73 |
+
message_count: int = 0
|
| 74 |
+
frames: dict[int, list[Frame | StreamType]] = field(default_factory=dict)
|
| 75 |
+
client_buf: bytearray = field(default_factory=bytearray)
|
| 76 |
+
server_buf: bytearray = field(default_factory=bytearray)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class Http3Contentview(Contentview):
|
| 80 |
+
def __init__(self) -> None:
|
| 81 |
+
self.connections: defaultdict[tcp.TCPFlow, ConnectionState] = defaultdict(
|
| 82 |
+
ConnectionState
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def name(self) -> str:
|
| 87 |
+
return "HTTP/3 Frames"
|
| 88 |
+
|
| 89 |
+
def prettify(self, data: bytes, metadata: Metadata) -> str:
|
| 90 |
+
flow = metadata.flow
|
| 91 |
+
tcp_message = metadata.tcp_message
|
| 92 |
+
assert isinstance(flow, tcp.TCPFlow)
|
| 93 |
+
assert tcp_message
|
| 94 |
+
|
| 95 |
+
state = self.connections[flow]
|
| 96 |
+
|
| 97 |
+
for message in flow.messages[state.message_count :]:
|
| 98 |
+
if message.from_client:
|
| 99 |
+
buf = state.client_buf
|
| 100 |
+
else:
|
| 101 |
+
buf = state.server_buf
|
| 102 |
+
buf += message.content
|
| 103 |
+
|
| 104 |
+
if state.message_count == 0 and flow.metadata["quic_is_unidirectional"]:
|
| 105 |
+
h3_buf = Buffer(data=bytes(buf[:8]))
|
| 106 |
+
stream_type = h3_buf.pull_uint_var()
|
| 107 |
+
consumed = h3_buf.tell()
|
| 108 |
+
del buf[:consumed]
|
| 109 |
+
state.frames[0] = [StreamType(stream_type)]
|
| 110 |
+
|
| 111 |
+
while True:
|
| 112 |
+
h3_buf = Buffer(data=bytes(buf[:16]))
|
| 113 |
+
try:
|
| 114 |
+
frame_type = h3_buf.pull_uint_var()
|
| 115 |
+
frame_size = h3_buf.pull_uint_var()
|
| 116 |
+
except BufferReadError:
|
| 117 |
+
break
|
| 118 |
+
|
| 119 |
+
consumed = h3_buf.tell()
|
| 120 |
+
|
| 121 |
+
if len(buf) < consumed + frame_size:
|
| 122 |
+
break
|
| 123 |
+
|
| 124 |
+
frame_data = bytes(buf[consumed : consumed + frame_size])
|
| 125 |
+
|
| 126 |
+
frame = Frame(frame_type, frame_data)
|
| 127 |
+
|
| 128 |
+
state.frames.setdefault(state.message_count, []).append(frame)
|
| 129 |
+
|
| 130 |
+
del buf[: consumed + frame_size]
|
| 131 |
+
|
| 132 |
+
state.message_count += 1
|
| 133 |
+
|
| 134 |
+
frames = state.frames.get(flow.messages.index(tcp_message), [])
|
| 135 |
+
if not frames:
|
| 136 |
+
return ""
|
| 137 |
+
else:
|
| 138 |
+
return "\n\n".join(frame.pretty() for frame in frames)
|
| 139 |
+
|
| 140 |
+
def render_priority(
|
| 141 |
+
self,
|
| 142 |
+
data: bytes,
|
| 143 |
+
metadata: Metadata,
|
| 144 |
+
) -> float:
|
| 145 |
+
flow = metadata.flow
|
| 146 |
+
return (
|
| 147 |
+
2
|
| 148 |
+
* float(bool(flow and is_h3_alpn(flow.client_conn.alpn)))
|
| 149 |
+
* float(isinstance(flow, tcp.TCPFlow))
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
http3 = Http3Contentview()
|