mozproxy 1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mozproxy/__init__.py +44 -0
- mozproxy/__main__.py +10 -0
- mozproxy/backends/__init__.py +3 -0
- mozproxy/backends/base.py +29 -0
- mozproxy/backends/mitm/__init__.py +6 -0
- mozproxy/backends/mitm/android.py +245 -0
- mozproxy/backends/mitm/desktop.py +161 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-osx-arm64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-win.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-osx-arm64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-win.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-win.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-win.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-win.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-win.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-win.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-linux64.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-osx.manifest +10 -0
- mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-win.manifest +10 -0
- mozproxy/backends/mitm/mitm.py +507 -0
- mozproxy/backends/mitm/mitmproxy_requirements.txt +34 -0
- mozproxy/backends/mitm/scripts/__init__.py +4 -0
- mozproxy/backends/mitm/scripts/alt-serverplayback.py +262 -0
- mozproxy/backends/mitm/scripts/alternate-server-replay.py +310 -0
- mozproxy/backends/mitm/scripts/catapult/LICENSE +27 -0
- mozproxy/backends/mitm/scripts/catapult/deterministic.js +71 -0
- mozproxy/backends/mitm/scripts/http_protocol_extractor.py +83 -0
- mozproxy/backends/mitm/scripts/inject-deterministic.py +198 -0
- mozproxy/driver.py +168 -0
- mozproxy/recordings.py +163 -0
- mozproxy/server.py +26 -0
- mozproxy/utils.py +257 -0
- mozproxy-1.0.dist-info/METADATA +33 -0
- mozproxy-1.0.dist-info/RECORD +51 -0
- mozproxy-1.0.dist-info/WHEEL +5 -0
- mozproxy-1.0.dist-info/entry_points.txt +2 -0
- mozproxy-1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# This Source Code Form is subject to the terms of the Mozilla Public
|
|
2
|
+
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
3
|
+
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
4
|
+
|
|
5
|
+
# This file was copied from
|
|
6
|
+
# https://github.com/mitmproxy/mitmproxy/blob/v7.0.4/mitmproxy/addons/serverplayback.py
|
|
7
|
+
# and modified by Kimberly Sereduck
|
|
8
|
+
|
|
9
|
+
# Altered features:
|
|
10
|
+
# * request function returns 404 rather than killing the flow which results in test failure
|
|
11
|
+
# * added option to play flows in reverse order: alt_server_replay_order_reversed
|
|
12
|
+
# * TO DO: remove the replay packages that don't have any content in their response package,
|
|
13
|
+
# see Bug 1739418: https://bugzilla.mozilla.org/show_bug.cgi?id=1739418
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import traceback
|
|
17
|
+
import urllib
|
|
18
|
+
from collections.abc import Hashable, Sequence
|
|
19
|
+
from typing import Any, Optional
|
|
20
|
+
|
|
21
|
+
import mitmproxy.types
|
|
22
|
+
from mitmproxy import command, ctx, exceptions, flow, hooks, http, io
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AltServerPlayback:
|
|
26
|
+
flowmap: dict[Hashable, list[http.HTTPFlow]]
|
|
27
|
+
configured: bool
|
|
28
|
+
|
|
29
|
+
def __init__(self):
|
|
30
|
+
self.flowmap = {}
|
|
31
|
+
self.configured = False
|
|
32
|
+
|
|
33
|
+
def load(self, loader):
|
|
34
|
+
loader.add_option(
|
|
35
|
+
"alt_server_replay_kill_extra",
|
|
36
|
+
bool,
|
|
37
|
+
False,
|
|
38
|
+
"Kill extra requests during replay.",
|
|
39
|
+
)
|
|
40
|
+
loader.add_option(
|
|
41
|
+
"alt_server_replay_nopop",
|
|
42
|
+
bool,
|
|
43
|
+
False,
|
|
44
|
+
"""
|
|
45
|
+
Don't remove flows from server replay state after use. This makes it
|
|
46
|
+
possible to replay same response multiple times.
|
|
47
|
+
""",
|
|
48
|
+
)
|
|
49
|
+
loader.add_option(
|
|
50
|
+
"alt_server_replay_refresh",
|
|
51
|
+
bool,
|
|
52
|
+
True,
|
|
53
|
+
"""
|
|
54
|
+
Refresh server replay responses by adjusting date, expires and
|
|
55
|
+
last-modified headers, as well as adjusting cookie expiration.
|
|
56
|
+
""",
|
|
57
|
+
)
|
|
58
|
+
loader.add_option(
|
|
59
|
+
"alt_server_replay_use_headers",
|
|
60
|
+
Sequence[str],
|
|
61
|
+
[],
|
|
62
|
+
"Request headers to be considered during replay.",
|
|
63
|
+
)
|
|
64
|
+
loader.add_option(
|
|
65
|
+
"alt_server_replay",
|
|
66
|
+
Sequence[str],
|
|
67
|
+
[],
|
|
68
|
+
"Replay server responses from a saved file.",
|
|
69
|
+
)
|
|
70
|
+
loader.add_option(
|
|
71
|
+
"alt_server_replay_ignore_content",
|
|
72
|
+
bool,
|
|
73
|
+
False,
|
|
74
|
+
"Ignore request's content while searching for a saved flow to replay.",
|
|
75
|
+
)
|
|
76
|
+
loader.add_option(
|
|
77
|
+
"alt_server_replay_ignore_params",
|
|
78
|
+
Sequence[str],
|
|
79
|
+
[],
|
|
80
|
+
"""
|
|
81
|
+
Request's parameters to be ignored while searching for a saved flow
|
|
82
|
+
to replay.
|
|
83
|
+
""",
|
|
84
|
+
)
|
|
85
|
+
loader.add_option(
|
|
86
|
+
"alt_server_replay_ignore_payload_params",
|
|
87
|
+
Sequence[str],
|
|
88
|
+
[],
|
|
89
|
+
"""
|
|
90
|
+
Request's payload parameters (application/x-www-form-urlencoded or
|
|
91
|
+
multipart/form-data) to be ignored while searching for a saved flow
|
|
92
|
+
to replay.
|
|
93
|
+
""",
|
|
94
|
+
)
|
|
95
|
+
loader.add_option(
|
|
96
|
+
"alt_server_replay_ignore_host",
|
|
97
|
+
bool,
|
|
98
|
+
False,
|
|
99
|
+
"""
|
|
100
|
+
Ignore request's destination host while searching for a saved flow
|
|
101
|
+
to replay.
|
|
102
|
+
""",
|
|
103
|
+
)
|
|
104
|
+
loader.add_option(
|
|
105
|
+
"alt_server_replay_ignore_port",
|
|
106
|
+
bool,
|
|
107
|
+
False,
|
|
108
|
+
"""
|
|
109
|
+
Ignore request's destination port while searching for a saved flow
|
|
110
|
+
to replay.
|
|
111
|
+
""",
|
|
112
|
+
)
|
|
113
|
+
loader.add_option(
|
|
114
|
+
"alt_server_replay_order_reversed",
|
|
115
|
+
bool,
|
|
116
|
+
False,
|
|
117
|
+
"""
|
|
118
|
+
Reverse the order of flows when replaying.
|
|
119
|
+
""",
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
@command.command("replay.server")
|
|
123
|
+
def load_flows(self, flows: Sequence[flow.Flow]) -> None:
|
|
124
|
+
"""
|
|
125
|
+
Replay server responses from flows.
|
|
126
|
+
"""
|
|
127
|
+
self.flowmap = {}
|
|
128
|
+
if ctx.options.alt_server_replay_order_reversed:
|
|
129
|
+
flows.reverse()
|
|
130
|
+
for f in flows:
|
|
131
|
+
if isinstance(f, http.HTTPFlow):
|
|
132
|
+
lst = self.flowmap.setdefault(self._hash(f), [])
|
|
133
|
+
lst.append(f)
|
|
134
|
+
ctx.master.addons.trigger(hooks.UpdateHook([]))
|
|
135
|
+
|
|
136
|
+
@command.command("replay.server.file")
|
|
137
|
+
def load_file(self, path: mitmproxy.types.Path) -> None:
|
|
138
|
+
try:
|
|
139
|
+
flows = io.read_flows_from_paths([path])
|
|
140
|
+
except exceptions.FlowReadException as e:
|
|
141
|
+
raise exceptions.CommandError(str(e))
|
|
142
|
+
self.load_flows(flows)
|
|
143
|
+
|
|
144
|
+
@command.command("replay.server.stop")
|
|
145
|
+
def clear(self) -> None:
|
|
146
|
+
"""
|
|
147
|
+
Stop server replay.
|
|
148
|
+
"""
|
|
149
|
+
self.flowmap = {}
|
|
150
|
+
ctx.master.addons.trigger(hooks.UpdateHook([]))
|
|
151
|
+
|
|
152
|
+
@command.command("replay.server.count")
|
|
153
|
+
def count(self) -> int:
|
|
154
|
+
return sum([len(i) for i in self.flowmap.values()])
|
|
155
|
+
|
|
156
|
+
def _hash(self, flow: http.HTTPFlow) -> Hashable:
|
|
157
|
+
"""
|
|
158
|
+
Calculates a loose hash of the flow request.
|
|
159
|
+
"""
|
|
160
|
+
r = flow.request
|
|
161
|
+
_, _, path, _, query, _ = urllib.parse.urlparse(r.url)
|
|
162
|
+
queriesArray = urllib.parse.parse_qsl(query, keep_blank_values=True)
|
|
163
|
+
|
|
164
|
+
key: list[Any] = [str(r.scheme), str(r.method), str(path)]
|
|
165
|
+
if not ctx.options.alt_server_replay_ignore_content:
|
|
166
|
+
if ctx.options.alt_server_replay_ignore_payload_params and r.multipart_form:
|
|
167
|
+
key.extend(
|
|
168
|
+
(k, v)
|
|
169
|
+
for k, v in r.multipart_form.items(multi=True)
|
|
170
|
+
if k.decode(errors="replace")
|
|
171
|
+
not in ctx.options.alt_server_replay_ignore_payload_params
|
|
172
|
+
)
|
|
173
|
+
elif (
|
|
174
|
+
ctx.options.alt_server_replay_ignore_payload_params
|
|
175
|
+
and r.urlencoded_form
|
|
176
|
+
):
|
|
177
|
+
key.extend(
|
|
178
|
+
(k, v)
|
|
179
|
+
for k, v in r.urlencoded_form.items(multi=True)
|
|
180
|
+
if k not in ctx.options.alt_server_replay_ignore_payload_params
|
|
181
|
+
)
|
|
182
|
+
else:
|
|
183
|
+
key.append(str(r.raw_content))
|
|
184
|
+
|
|
185
|
+
if not ctx.options.alt_server_replay_ignore_host:
|
|
186
|
+
key.append(r.pretty_host)
|
|
187
|
+
if not ctx.options.alt_server_replay_ignore_port:
|
|
188
|
+
key.append(r.port)
|
|
189
|
+
|
|
190
|
+
filtered = []
|
|
191
|
+
ignore_params = ctx.options.alt_server_replay_ignore_params or []
|
|
192
|
+
for p in queriesArray:
|
|
193
|
+
if p[0] not in ignore_params:
|
|
194
|
+
filtered.append(p)
|
|
195
|
+
for p in filtered:
|
|
196
|
+
key.append(p[0])
|
|
197
|
+
key.append(p[1])
|
|
198
|
+
|
|
199
|
+
if ctx.options.alt_server_replay_use_headers:
|
|
200
|
+
headers = []
|
|
201
|
+
for i in ctx.options.alt_server_replay_use_headers:
|
|
202
|
+
v = r.headers.get(i)
|
|
203
|
+
headers.append((i, v))
|
|
204
|
+
key.append(headers)
|
|
205
|
+
return hashlib.sha256(repr(key).encode("utf8", "surrogateescape")).digest()
|
|
206
|
+
|
|
207
|
+
def next_flow(self, flow: http.HTTPFlow) -> Optional[http.HTTPFlow]:
|
|
208
|
+
"""
|
|
209
|
+
Returns the next flow object, or None if no matching flow was
|
|
210
|
+
found.
|
|
211
|
+
"""
|
|
212
|
+
hash = self._hash(flow)
|
|
213
|
+
if hash in self.flowmap:
|
|
214
|
+
if ctx.options.alt_server_replay_nopop:
|
|
215
|
+
return next(
|
|
216
|
+
(flow for flow in self.flowmap[hash] if flow.response), None
|
|
217
|
+
)
|
|
218
|
+
else:
|
|
219
|
+
ret = self.flowmap[hash].pop(0)
|
|
220
|
+
while not ret.response:
|
|
221
|
+
if self.flowmap[hash]:
|
|
222
|
+
ret = self.flowmap[hash].pop(0)
|
|
223
|
+
else:
|
|
224
|
+
del self.flowmap[hash]
|
|
225
|
+
return None
|
|
226
|
+
if not self.flowmap[hash]:
|
|
227
|
+
del self.flowmap[hash]
|
|
228
|
+
return ret
|
|
229
|
+
else:
|
|
230
|
+
return None
|
|
231
|
+
|
|
232
|
+
def configure(self, updated):
|
|
233
|
+
if not self.configured and ctx.options.alt_server_replay:
|
|
234
|
+
self.configured = True
|
|
235
|
+
try:
|
|
236
|
+
flows = io.read_flows_from_paths(
|
|
237
|
+
ctx.options.alt_server_replay[0].split(",")
|
|
238
|
+
)
|
|
239
|
+
except exceptions.FlowReadException:
|
|
240
|
+
raise exceptions.OptionsError(str(traceback.print_exc()))
|
|
241
|
+
self.load_flows(flows)
|
|
242
|
+
|
|
243
|
+
def request(self, f: http.HTTPFlow) -> None:
|
|
244
|
+
if self.flowmap:
|
|
245
|
+
rflow = self.next_flow(f)
|
|
246
|
+
if rflow:
|
|
247
|
+
assert rflow.response
|
|
248
|
+
response = rflow.response.copy()
|
|
249
|
+
if ctx.options.alt_server_replay_refresh:
|
|
250
|
+
response.refresh()
|
|
251
|
+
f.response = response
|
|
252
|
+
f.is_replay = "response"
|
|
253
|
+
elif ctx.options.alt_server_replay_kill_extra:
|
|
254
|
+
ctx.log.warn(
|
|
255
|
+
f"server_playback: killed non-replay request {f.request.url}"
|
|
256
|
+
)
|
|
257
|
+
f.response = http.Response.make(
|
|
258
|
+
404, b"", {"content-type": "text/plain"}
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
addons = [AltServerPlayback()]
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
# This Source Code Form is subject to the terms of the Mozilla Public
|
|
2
|
+
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
3
|
+
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
4
|
+
|
|
5
|
+
# This file was copied from mitmproxy/mitmproxy/addons/serverplayback.py release tag 4.0.4
|
|
6
|
+
# and modified by Florin Strugariu
|
|
7
|
+
|
|
8
|
+
# Altered features:
|
|
9
|
+
# * returns 404 rather than dropping the whole HTTP/2 connection on the floor
|
|
10
|
+
# * remove the replay packages that don't have any content in their response package
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import signal
|
|
15
|
+
import time
|
|
16
|
+
import typing
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
from urllib.parse import parse_qsl, unquote, urlparse
|
|
19
|
+
|
|
20
|
+
from mitmproxy import ctx, exceptions, http, io
|
|
21
|
+
|
|
22
|
+
# PATCHING AREA - ALLOWS HTTP/2 WITH NO CERT SNIFFING
|
|
23
|
+
from mitmproxy.proxy.protocol import tls
|
|
24
|
+
from mitmproxy.proxy.protocol.http2 import Http2Layer, SafeH2Connection
|
|
25
|
+
|
|
26
|
+
_PROTO = {}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def _alpn(self):
|
|
31
|
+
proto = _PROTO.get(self.server_sni)
|
|
32
|
+
if proto is None:
|
|
33
|
+
return self.server_conn.get_alpn_proto_negotiated()
|
|
34
|
+
if proto.startswith("HTTP/2"):
|
|
35
|
+
return b"h2"
|
|
36
|
+
elif proto.startswith("HTTP/1"):
|
|
37
|
+
return b"h1"
|
|
38
|
+
return b""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
tls.TlsLayer.alpn_for_client_connection = _alpn
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _server_conn(self):
|
|
45
|
+
if not self.server_conn.connected() and self.server_conn not in self.connections:
|
|
46
|
+
# we can't use ctx.log in this layer
|
|
47
|
+
print("Ignored CONNECT call on upstream server")
|
|
48
|
+
return
|
|
49
|
+
if self.server_conn.connected():
|
|
50
|
+
import h2.config
|
|
51
|
+
|
|
52
|
+
config = h2.config.H2Configuration(
|
|
53
|
+
client_side=True,
|
|
54
|
+
header_encoding=False,
|
|
55
|
+
validate_outbound_headers=False,
|
|
56
|
+
validate_inbound_headers=False,
|
|
57
|
+
)
|
|
58
|
+
self.connections[self.server_conn] = SafeH2Connection(
|
|
59
|
+
self.server_conn, config=config
|
|
60
|
+
)
|
|
61
|
+
self.connections[self.server_conn].initiate_connection()
|
|
62
|
+
self.server_conn.send(self.connections[self.server_conn].data_to_send())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
Http2Layer._initiate_server_conn = _server_conn
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _remote_settings_changed(self, event, other_conn):
|
|
69
|
+
if other_conn not in self.connections:
|
|
70
|
+
# we can't use ctx.log in this layer
|
|
71
|
+
print("Ignored remote settings upstream")
|
|
72
|
+
return True
|
|
73
|
+
new_settings = dict([
|
|
74
|
+
(key, cs.new_value) for (key, cs) in event.changed_settings.items()
|
|
75
|
+
])
|
|
76
|
+
self.connections[other_conn].safe_update_settings(new_settings)
|
|
77
|
+
return True
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
Http2Layer._handle_remote_settings_changed = _remote_settings_changed
|
|
81
|
+
# END OF PATCHING
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class AlternateServerPlayback:
|
|
85
|
+
def __init__(self):
|
|
86
|
+
ctx.master.addons.remove(ctx.master.addons.get("serverplayback"))
|
|
87
|
+
self.flowmap = {}
|
|
88
|
+
self.configured = False
|
|
89
|
+
self.netlocs = defaultdict(lambda: defaultdict(int))
|
|
90
|
+
self.calls = []
|
|
91
|
+
self._done = False
|
|
92
|
+
self._replayed = 0
|
|
93
|
+
self._not_replayed = 0
|
|
94
|
+
self._recordings_used = 0
|
|
95
|
+
self.mitm_version = ctx.mitmproxy.version.VERSION
|
|
96
|
+
|
|
97
|
+
ctx.log.info("MitmProxy version: %s" % self.mitm_version)
|
|
98
|
+
|
|
99
|
+
def load(self, loader):
|
|
100
|
+
loader.add_option(
|
|
101
|
+
"server_replay_files",
|
|
102
|
+
typing.Sequence[str],
|
|
103
|
+
[],
|
|
104
|
+
"Replay server responses from a saved file.",
|
|
105
|
+
)
|
|
106
|
+
loader.add_option(
|
|
107
|
+
"upload_dir",
|
|
108
|
+
str,
|
|
109
|
+
"",
|
|
110
|
+
"Upload directory",
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def load_flows(self, flows):
|
|
114
|
+
"""
|
|
115
|
+
Replay server responses from flows.
|
|
116
|
+
"""
|
|
117
|
+
for i in flows:
|
|
118
|
+
if i.type == "websocket":
|
|
119
|
+
# Mitmproxy can't replay WebSocket packages.
|
|
120
|
+
ctx.log.info(
|
|
121
|
+
"Recorded response is a WebSocketFlow. Removing from recording list as"
|
|
122
|
+
" WebSockets are disabled"
|
|
123
|
+
)
|
|
124
|
+
elif i.response:
|
|
125
|
+
hash = self._hash(i)
|
|
126
|
+
if i.response.content is None and self.flowmap.get(hash, False):
|
|
127
|
+
# To avoid 'Cannot assemble flow with missing content' we check
|
|
128
|
+
# if the correct request has no content and hashed request already exists
|
|
129
|
+
# if the hashed request already has content
|
|
130
|
+
# then we do not add the new one end keep the existing one
|
|
131
|
+
|
|
132
|
+
if not self.flowmap.get(hash)["flow"].response.content is None:
|
|
133
|
+
ctx.log.info(
|
|
134
|
+
"Duplicate recorded request found with content missing. "
|
|
135
|
+
"Removing current request as it has no data. %s"
|
|
136
|
+
% i.request.url
|
|
137
|
+
)
|
|
138
|
+
continue
|
|
139
|
+
|
|
140
|
+
f = self.flowmap.setdefault(hash, {"flow": None, "reply_count": 0})
|
|
141
|
+
# overwrite with new flow if already hashed
|
|
142
|
+
f["flow"] = i
|
|
143
|
+
|
|
144
|
+
else:
|
|
145
|
+
ctx.log.info(
|
|
146
|
+
"Recorded request %s has no response. Removing from recording list"
|
|
147
|
+
% i.request.url
|
|
148
|
+
)
|
|
149
|
+
ctx.master.addons.trigger("update", [])
|
|
150
|
+
|
|
151
|
+
def load_files(self, paths):
|
|
152
|
+
try:
|
|
153
|
+
if "," in paths[0]:
|
|
154
|
+
paths = paths[0].split(",")
|
|
155
|
+
for path in paths:
|
|
156
|
+
ctx.log.info("Loading flows from %s" % path)
|
|
157
|
+
if not os.path.exists(path):
|
|
158
|
+
raise Exception("File does not exist!")
|
|
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
|
+
proto = os.path.join(os.path.dirname(path), "metadata.json")
|
|
165
|
+
if os.path.exists(proto):
|
|
166
|
+
ctx.log.info("Loading proto info from %s" % proto)
|
|
167
|
+
with open(proto) as f:
|
|
168
|
+
recording_info = json.loads(f.read())
|
|
169
|
+
if recording_info.get("http_protocol", False):
|
|
170
|
+
ctx.log.info(
|
|
171
|
+
"Replaying file {} recorded on {}".format(
|
|
172
|
+
path, recording_info["recording_date"]
|
|
173
|
+
)
|
|
174
|
+
)
|
|
175
|
+
_PROTO.update(recording_info["http_protocol"])
|
|
176
|
+
else:
|
|
177
|
+
ctx.log.warn(
|
|
178
|
+
f"Replaying file {proto} has no http_protocol info."
|
|
179
|
+
)
|
|
180
|
+
except Exception as e:
|
|
181
|
+
ctx.log.error("Could not load recording file! Stopping playback process!")
|
|
182
|
+
ctx.log.error(str(e))
|
|
183
|
+
ctx.master.shutdown()
|
|
184
|
+
|
|
185
|
+
def _hash(self, flow):
|
|
186
|
+
"""
|
|
187
|
+
Calculates a loose hash of the flow request.
|
|
188
|
+
"""
|
|
189
|
+
r = flow.request
|
|
190
|
+
|
|
191
|
+
# unquote url
|
|
192
|
+
# See Bug 1509835
|
|
193
|
+
_, _, path, _, query, _ = urlparse(unquote(r.url))
|
|
194
|
+
queriesArray = parse_qsl(query, keep_blank_values=True)
|
|
195
|
+
|
|
196
|
+
key = [str(r.port), str(r.scheme), str(r.method), str(path)]
|
|
197
|
+
key.append(str(r.raw_content))
|
|
198
|
+
key.append(r.host)
|
|
199
|
+
|
|
200
|
+
for p in queriesArray:
|
|
201
|
+
key.append(p[0])
|
|
202
|
+
key.append(p[1])
|
|
203
|
+
|
|
204
|
+
return hashlib.sha256(repr(key).encode("utf8", "surrogateescape")).digest()
|
|
205
|
+
|
|
206
|
+
def next_flow(self, request):
|
|
207
|
+
"""
|
|
208
|
+
Returns the next flow object, or None if no matching flow was
|
|
209
|
+
found.
|
|
210
|
+
"""
|
|
211
|
+
hsh = self._hash(request)
|
|
212
|
+
if hsh in self.flowmap:
|
|
213
|
+
if self.flowmap[hsh]["reply_count"] == 0:
|
|
214
|
+
self._recordings_used += 1
|
|
215
|
+
self.flowmap[hsh]["reply_count"] += 1
|
|
216
|
+
# return the most recently added flow with this hash
|
|
217
|
+
return self.flowmap[hsh]["flow"]
|
|
218
|
+
|
|
219
|
+
def configure(self, updated):
|
|
220
|
+
if not self.configured and ctx.options.server_replay_files:
|
|
221
|
+
self.configured = True
|
|
222
|
+
self.load_files(ctx.options.server_replay_files)
|
|
223
|
+
|
|
224
|
+
def done(self):
|
|
225
|
+
if self._done or not ctx.options.upload_dir:
|
|
226
|
+
return
|
|
227
|
+
|
|
228
|
+
replay_confidence = float(self._replayed) / (
|
|
229
|
+
self._replayed + self._not_replayed
|
|
230
|
+
)
|
|
231
|
+
recording_proportion_used = (
|
|
232
|
+
0
|
|
233
|
+
if self._recordings_used == 0
|
|
234
|
+
else float(self._recordings_used) / len(self.flowmap)
|
|
235
|
+
)
|
|
236
|
+
stats = {
|
|
237
|
+
"totals": dict(self.netlocs),
|
|
238
|
+
"calls": self.calls,
|
|
239
|
+
"replayed": self._replayed,
|
|
240
|
+
"not-replayed": self._not_replayed,
|
|
241
|
+
"replay-confidence": int(replay_confidence * 100),
|
|
242
|
+
"recording-proportion-used": int(recording_proportion_used * 100),
|
|
243
|
+
}
|
|
244
|
+
file_name = (
|
|
245
|
+
"mitm_netlocs_%s.json"
|
|
246
|
+
% os.path.splitext(os.path.basename(ctx.options.server_replay_files[0]))[0]
|
|
247
|
+
)
|
|
248
|
+
path = os.path.normpath(os.path.join(ctx.options.upload_dir, file_name))
|
|
249
|
+
try:
|
|
250
|
+
with open(path, "w") as f:
|
|
251
|
+
f.write(json.dumps(stats, indent=2, sort_keys=True))
|
|
252
|
+
finally:
|
|
253
|
+
self._done = True
|
|
254
|
+
|
|
255
|
+
def request(self, f):
|
|
256
|
+
if self.flowmap:
|
|
257
|
+
try:
|
|
258
|
+
rflow = self.next_flow(f)
|
|
259
|
+
if rflow:
|
|
260
|
+
response = rflow.response.copy()
|
|
261
|
+
response.is_replay = True
|
|
262
|
+
# Refresh server replay responses by adjusting date, expires and
|
|
263
|
+
# last-modified headers, as well as adjusting cookie expiration.
|
|
264
|
+
response.refresh()
|
|
265
|
+
|
|
266
|
+
f.response = response
|
|
267
|
+
self._replayed += 1
|
|
268
|
+
else:
|
|
269
|
+
# returns 404 rather than dropping the whole HTTP/2 connection
|
|
270
|
+
ctx.log.warn(
|
|
271
|
+
f"server_playback: killed non-replay request {f.request.url}"
|
|
272
|
+
)
|
|
273
|
+
f.response = http.HTTPResponse.make(
|
|
274
|
+
404, b"", {"content-type": "text/plain"}
|
|
275
|
+
)
|
|
276
|
+
self._not_replayed += 1
|
|
277
|
+
|
|
278
|
+
# collecting stats only if we can dump them (see .done())
|
|
279
|
+
if ctx.options.upload_dir:
|
|
280
|
+
parsed_url = urlparse(unquote(f.request.url))
|
|
281
|
+
self.netlocs[parsed_url.netloc][f.response.status_code] += 1
|
|
282
|
+
self.calls.append({
|
|
283
|
+
"time": str(time.time()),
|
|
284
|
+
"url": f.request.url,
|
|
285
|
+
"response_status": f.response.status_code,
|
|
286
|
+
})
|
|
287
|
+
except Exception as e:
|
|
288
|
+
ctx.log.error("Could not generate response! Stopping playback process!")
|
|
289
|
+
ctx.log.info(e)
|
|
290
|
+
ctx.master.shutdown()
|
|
291
|
+
|
|
292
|
+
else:
|
|
293
|
+
ctx.log.error("Playback library is empty! Stopping playback process!")
|
|
294
|
+
ctx.master.shutdown()
|
|
295
|
+
return
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
playback = AlternateServerPlayback()
|
|
299
|
+
|
|
300
|
+
if hasattr(signal, "SIGBREAK"):
|
|
301
|
+
# allows the addon to dump the stats even if mitmproxy
|
|
302
|
+
# does not call done() like on windows termination
|
|
303
|
+
# for this, the parent process sends CTRL_BREAK_EVENT which
|
|
304
|
+
# is received as an SIGBREAK event
|
|
305
|
+
def _shutdown(sig, frame):
|
|
306
|
+
ctx.master.shutdown()
|
|
307
|
+
|
|
308
|
+
signal.signal(signal.SIGBREAK, _shutdown)
|
|
309
|
+
|
|
310
|
+
addons = [playback]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Copyright 2015 The Chromium Authors. All rights reserved.
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without
|
|
4
|
+
modification, are permitted provided that the following conditions are met:
|
|
5
|
+
|
|
6
|
+
* Redistributions of source code must retain the above copyright notice, this
|
|
7
|
+
list of conditions and the following disclaimer.
|
|
8
|
+
|
|
9
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
10
|
+
this list of conditions and the following disclaimer in the documentation
|
|
11
|
+
and/or other materials provided with the distribution.
|
|
12
|
+
|
|
13
|
+
* Neither the name of catapult nor the names of its
|
|
14
|
+
contributors may be used to endorse or promote products derived from
|
|
15
|
+
this software without specific prior written permission.
|
|
16
|
+
|
|
17
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
18
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
19
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
20
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
21
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
22
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
23
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
24
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
25
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
26
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
27
|
+
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
2
|
+
// Use of this source code is governed by a BSD-style license that can be
|
|
3
|
+
// found in the LICENSE file.
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
(function () {
|
|
9
|
+
var random_count = 0;
|
|
10
|
+
var random_count_threshold = 25;
|
|
11
|
+
var random_seed = 0.462;
|
|
12
|
+
Math.random = function() {
|
|
13
|
+
random_count++;
|
|
14
|
+
if (random_count > random_count_threshold){
|
|
15
|
+
random_seed += 0.1;
|
|
16
|
+
random_count = 1;
|
|
17
|
+
}
|
|
18
|
+
return (random_seed % 1);
|
|
19
|
+
};
|
|
20
|
+
if (typeof(crypto) == 'object' &&
|
|
21
|
+
typeof(crypto.getRandomValues) == 'function') {
|
|
22
|
+
crypto.getRandomValues = function(arr) {
|
|
23
|
+
var scale = Math.pow(256, arr.BYTES_PER_ELEMENT);
|
|
24
|
+
for (var i = 0; i < arr.length; i++) {
|
|
25
|
+
arr[i] = Math.floor(Math.random() * scale);
|
|
26
|
+
}
|
|
27
|
+
return arr;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
})();
|
|
31
|
+
(function () {
|
|
32
|
+
var date_count = 0;
|
|
33
|
+
var date_count_threshold = 25;
|
|
34
|
+
var orig_date = Date;
|
|
35
|
+
// Time since epoch in milliseconds. This is replaced by script injector with
|
|
36
|
+
// the date when the recording is done.
|
|
37
|
+
var time_seed = REPLACE_LOAD_TIMESTAMP;
|
|
38
|
+
Date = function() {
|
|
39
|
+
if (this instanceof Date) {
|
|
40
|
+
date_count++;
|
|
41
|
+
if (date_count > date_count_threshold){
|
|
42
|
+
time_seed += 50;
|
|
43
|
+
date_count = 1;
|
|
44
|
+
}
|
|
45
|
+
switch (arguments.length) {
|
|
46
|
+
case 0: return new orig_date(time_seed);
|
|
47
|
+
case 1: return new orig_date(arguments[0]);
|
|
48
|
+
default: return new orig_date(arguments[0], arguments[1],
|
|
49
|
+
arguments.length >= 3 ? arguments[2] : 1,
|
|
50
|
+
arguments.length >= 4 ? arguments[3] : 0,
|
|
51
|
+
arguments.length >= 5 ? arguments[4] : 0,
|
|
52
|
+
arguments.length >= 6 ? arguments[5] : 0,
|
|
53
|
+
arguments.length >= 7 ? arguments[6] : 0);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return new Date().toString();
|
|
57
|
+
};
|
|
58
|
+
Date.__proto__ = orig_date;
|
|
59
|
+
Date.prototype = orig_date.prototype;
|
|
60
|
+
Date.prototype.constructor = Date;
|
|
61
|
+
orig_date.now = function() {
|
|
62
|
+
return new Date().getTime();
|
|
63
|
+
};
|
|
64
|
+
orig_date.prototype.getTimezoneOffset = function() {
|
|
65
|
+
var dst2010Start = 1268560800000;
|
|
66
|
+
var dst2010End = 1289120400000;
|
|
67
|
+
if (this.getTime() >= dst2010Start && this.getTime() < dst2010End)
|
|
68
|
+
return 420;
|
|
69
|
+
return 480;
|
|
70
|
+
};
|
|
71
|
+
})();
|