-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
export.py
215 lines (177 loc) · 6.82 KB
/
export.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import logging
import shlex
from collections.abc import Callable
from collections.abc import Sequence
from typing import Any
import pyperclip
import mitmproxy.types
from mitmproxy import command
from mitmproxy import ctx
from mitmproxy import exceptions
from mitmproxy import flow
from mitmproxy import http
from mitmproxy.net.http.http1 import assemble
from mitmproxy.utils import strutils
def cleanup_request(f: flow.Flow) -> http.Request:
if not getattr(f, "request", None):
raise exceptions.CommandError("Can't export flow with no request.")
assert isinstance(f, http.HTTPFlow)
request = f.request.copy()
request.decode(strict=False)
return request
def pop_headers(request: http.Request) -> http.Request:
# Remove some headers that are redundant for curl/httpie export
request.headers.pop("content-length")
if request.headers.get("host", "") == request.host:
request.headers.pop("host")
if request.headers.get(":authority", "") == request.host:
request.headers.pop(":authority")
return request
def cleanup_response(f: flow.Flow) -> http.Response:
if not getattr(f, "response", None):
raise exceptions.CommandError("Can't export flow with no response.")
assert isinstance(f, http.HTTPFlow)
response = f.response.copy() # type: ignore
response.decode(strict=False)
return response
def request_content_for_console(request: http.Request) -> str:
try:
text = request.get_text(strict=True)
assert text
except ValueError:
# shlex.quote doesn't support a bytes object
# see https://github.com/python/cpython/pull/10871
raise exceptions.CommandError("Request content must be valid unicode")
escape_control_chars = {chr(i): f"\\x{i:02x}" for i in range(32)}
return "".join(escape_control_chars.get(x, x) for x in text)
def curl_command(f: flow.Flow) -> str:
request = cleanup_request(f)
request = pop_headers(request)
args = ["curl"]
server_addr = f.server_conn.peername[0] if f.server_conn.peername else None
if (
ctx.options.export_preserve_original_ip
and server_addr
and request.pretty_host != server_addr
):
resolve = f"{request.pretty_host}:{request.port}:[{server_addr}]"
args.append("--resolve")
args.append(resolve)
for k, v in request.headers.items(multi=True):
if k.lower() == "accept-encoding":
args.append("--compressed")
else:
args += ["-H", f"{k}: {v}"]
if request.method != "GET":
args += ["-X", request.method]
args.append(request.pretty_url)
if request.content:
args += ["-d", request_content_for_console(request)]
return " ".join(shlex.quote(arg) for arg in args)
def httpie_command(f: flow.Flow) -> str:
request = cleanup_request(f)
request = pop_headers(request)
# TODO: Once https://github.com/httpie/httpie/issues/414 is implemented, we
# should ensure we always connect to the IP address specified in the flow,
# similar to how it's done in curl_command.
url = request.pretty_url
args = ["http", request.method, url]
for k, v in request.headers.items(multi=True):
args.append(f"{k}: {v}")
cmd = " ".join(shlex.quote(arg) for arg in args)
if request.content:
cmd += " <<< " + shlex.quote(request_content_for_console(request))
return cmd
def raw_request(f: flow.Flow) -> bytes:
request = cleanup_request(f)
if request.raw_content is None:
raise exceptions.CommandError("Request content missing.")
return assemble.assemble_request(request)
def raw_response(f: flow.Flow) -> bytes:
response = cleanup_response(f)
if response.raw_content is None:
raise exceptions.CommandError("Response content missing.")
return assemble.assemble_response(response)
def raw(f: flow.Flow, separator=b"\r\n\r\n") -> bytes:
"""Return either the request or response if only one exists, otherwise return both"""
request_present = (
isinstance(f, http.HTTPFlow) and f.request and f.request.raw_content is not None
)
response_present = (
isinstance(f, http.HTTPFlow)
and f.response
and f.response.raw_content is not None
)
if request_present and response_present:
parts = [raw_request(f), raw_response(f)]
if isinstance(f, http.HTTPFlow) and f.websocket:
parts.append(f.websocket._get_formatted_messages())
return separator.join(parts)
elif request_present:
return raw_request(f)
elif response_present:
return raw_response(f)
else:
raise exceptions.CommandError("Can't export flow with no request or response.")
formats: dict[str, Callable[[flow.Flow], str | bytes]] = dict(
curl=curl_command,
httpie=httpie_command,
raw=raw,
raw_request=raw_request,
raw_response=raw_response,
)
class Export:
def load(self, loader):
loader.add_option(
"export_preserve_original_ip",
bool,
False,
"""
When exporting a request as an external command, make an effort to
connect to the same IP as in the original request. This helps with
reproducibility in cases where the behaviour depends on the
particular host we are connecting to. Currently this only affects
curl exports.
""",
)
@command.command("export.formats")
def formats(self) -> Sequence[str]:
"""
Return a list of the supported export formats.
"""
return list(sorted(formats.keys()))
@command.command("export.file")
def file(self, format: str, flow: flow.Flow, path: mitmproxy.types.Path) -> None:
"""
Export a flow to path.
"""
if format not in formats:
raise exceptions.CommandError("No such export format: %s" % format)
func: Any = formats[format]
v = func(flow)
try:
with open(path, "wb") as fp:
if isinstance(v, bytes):
fp.write(v)
else:
fp.write(v.encode("utf-8"))
except OSError as e:
logging.error(str(e))
@command.command("export.clip")
def clip(self, format: str, f: flow.Flow) -> None:
"""
Export a flow to the system clipboard.
"""
try:
pyperclip.copy(self.export_str(format, f))
except pyperclip.PyperclipException as e:
logging.error(str(e))
@command.command("export")
def export_str(self, format: str, f: flow.Flow) -> str:
"""
Export a flow and return the result.
"""
if format not in formats:
raise exceptions.CommandError("No such export format: %s" % format)
func = formats[format]
return strutils.always_str(func(f), "utf8", "backslashreplace")