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,83 @@
|
|
|
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
|
+
import datetime
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import urllib
|
|
9
|
+
from urllib import parse
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HttpProtocolExtractor:
|
|
13
|
+
def get_ctx(self):
|
|
14
|
+
from mitmproxy import ctx
|
|
15
|
+
|
|
16
|
+
return ctx
|
|
17
|
+
|
|
18
|
+
def load(self, loader):
|
|
19
|
+
self.ctx = self.get_ctx()
|
|
20
|
+
|
|
21
|
+
self.request_protocol = {}
|
|
22
|
+
self.hashes = []
|
|
23
|
+
self.request_count = 0
|
|
24
|
+
|
|
25
|
+
self.ctx.log.info("Init Http Protocol extractor JS")
|
|
26
|
+
|
|
27
|
+
def _hash(self, flow):
|
|
28
|
+
"""
|
|
29
|
+
Calculates a loose hash of the flow request.
|
|
30
|
+
"""
|
|
31
|
+
r = flow.request
|
|
32
|
+
|
|
33
|
+
# unquote url
|
|
34
|
+
# See Bug 1509835
|
|
35
|
+
_, _, path, _, query, _ = urllib.parse.urlparse(parse.unquote(r.url))
|
|
36
|
+
queriesArray = urllib.parse.parse_qsl(query, keep_blank_values=True)
|
|
37
|
+
|
|
38
|
+
key = [str(r.port), str(r.scheme), str(r.method), str(path)]
|
|
39
|
+
key.append(str(r.raw_content))
|
|
40
|
+
key.append(r.host)
|
|
41
|
+
|
|
42
|
+
for p in queriesArray:
|
|
43
|
+
key.append(p[0])
|
|
44
|
+
key.append(p[1])
|
|
45
|
+
|
|
46
|
+
return hashlib.sha256(repr(key).encode("utf8", "surrogateescape")).digest()
|
|
47
|
+
|
|
48
|
+
def response(self, flow):
|
|
49
|
+
self.request_count += 1
|
|
50
|
+
hash = self._hash(flow)
|
|
51
|
+
if hash not in self.hashes:
|
|
52
|
+
self.hashes.append(hash)
|
|
53
|
+
|
|
54
|
+
if flow.type == "websocket":
|
|
55
|
+
self.ctx.log.info("Response is a WebSocketFlow. Bug 1559117")
|
|
56
|
+
else:
|
|
57
|
+
self.ctx.log.info(
|
|
58
|
+
"Response using protocol: %s" % flow.response.data.http_version
|
|
59
|
+
)
|
|
60
|
+
self.request_protocol[urllib.parse.urlparse(flow.request.url).netloc] = (
|
|
61
|
+
flow.response.data.http_version.decode("utf-8")
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def done(self):
|
|
65
|
+
output_json = {}
|
|
66
|
+
|
|
67
|
+
output_json["recording_date"] = str(datetime.datetime.now())
|
|
68
|
+
output_json["http_protocol"] = self.request_protocol
|
|
69
|
+
output_json["recorded_requests"] = self.request_count
|
|
70
|
+
output_json["recorded_requests_unique"] = len(self.hashes)
|
|
71
|
+
|
|
72
|
+
recording_file_name = self.ctx.options.save_stream_file
|
|
73
|
+
|
|
74
|
+
json_file_name = os.path.join(
|
|
75
|
+
os.path.dirname(recording_file_name),
|
|
76
|
+
"%s.json" % os.path.basename(recording_file_name).split(".")[0],
|
|
77
|
+
)
|
|
78
|
+
print("Saving response protocol data to %s" % json_file_name)
|
|
79
|
+
with open(json_file_name, "w") as file:
|
|
80
|
+
file.write(json.dumps(output_json))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
addons = [HttpProtocolExtractor()]
|
|
@@ -0,0 +1,198 @@
|
|
|
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
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from os import path
|
|
9
|
+
|
|
10
|
+
from mitmproxy import ctx
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AddDeterministic:
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self.millis = int(round(time.time() * 1000))
|
|
16
|
+
ctx.log.info("Init Deterministic JS")
|
|
17
|
+
|
|
18
|
+
def load(self, loader):
|
|
19
|
+
ctx.log.info("Load Deterministic JS")
|
|
20
|
+
|
|
21
|
+
def get_csp_directives(self, test_header, headers):
|
|
22
|
+
csp = headers.get(test_header, "")
|
|
23
|
+
return [d.strip() for d in csp.split(";")]
|
|
24
|
+
|
|
25
|
+
def get_csp_script_sources(self, test_header, headers):
|
|
26
|
+
sources = []
|
|
27
|
+
for directive in self.get_csp_directives(test_header, headers):
|
|
28
|
+
if directive.startswith("script-src "):
|
|
29
|
+
sources = directive.split()[1:]
|
|
30
|
+
return sources
|
|
31
|
+
|
|
32
|
+
def get_nonce_from_headers(self, test_header, headers):
|
|
33
|
+
"""
|
|
34
|
+
get_nonce_from_headers returns the nonce token from a
|
|
35
|
+
Content-Security-Policy (CSP) header's script source directive.
|
|
36
|
+
|
|
37
|
+
Note:
|
|
38
|
+
For more background information on CSP and nonce, please refer to
|
|
39
|
+
https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/script-src
|
|
40
|
+
https://developers.google.com/web/fundamentals/security/csp/
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
for source in self.get_csp_script_sources(test_header, headers) or []:
|
|
44
|
+
if source.startswith("'nonce-"):
|
|
45
|
+
return source.partition("'nonce-")[-1][:-1]
|
|
46
|
+
|
|
47
|
+
def get_script_with_nonce(self, script, nonce=None):
|
|
48
|
+
"""
|
|
49
|
+
Given a nonce, get_script_with_nonce returns the injected script text with the nonce.
|
|
50
|
+
|
|
51
|
+
If nonce None, get_script_with_nonce returns the script block
|
|
52
|
+
without attaching a nonce attribute.
|
|
53
|
+
|
|
54
|
+
Note:
|
|
55
|
+
Some responses may specify a nonce inside their Content-Security-Policy,
|
|
56
|
+
script-src directive.
|
|
57
|
+
The script injector needs to set the injected script's nonce attribute to
|
|
58
|
+
open execute permission for the injected script.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
if nonce:
|
|
62
|
+
return f'<script nonce="{nonce}">{script}</script>'
|
|
63
|
+
return f"<script>{script}</script>"
|
|
64
|
+
|
|
65
|
+
def update_csp_script_src(self, test_header, headers, sha256):
|
|
66
|
+
"""
|
|
67
|
+
Update the CSP script directives with appropriate information
|
|
68
|
+
|
|
69
|
+
Without this permissions a page with a
|
|
70
|
+
restrictive CSP will not execute injected scripts.
|
|
71
|
+
|
|
72
|
+
Note:
|
|
73
|
+
For more background information on CSP, please refer to
|
|
74
|
+
https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/script-src
|
|
75
|
+
https://developers.google.com/web/fundamentals/security/csp/
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
sources = self.get_csp_script_sources(test_header, headers)
|
|
79
|
+
add_unsafe = True
|
|
80
|
+
|
|
81
|
+
for token in sources:
|
|
82
|
+
if token == "'unsafe-inline'":
|
|
83
|
+
add_unsafe = False
|
|
84
|
+
ctx.log.info("Contains unsafe-inline")
|
|
85
|
+
elif token.startswith("'sha"):
|
|
86
|
+
sources.append(f"'sha256-{sha256}'")
|
|
87
|
+
add_unsafe = False
|
|
88
|
+
ctx.log.info("Add sha hash directive")
|
|
89
|
+
break
|
|
90
|
+
|
|
91
|
+
if add_unsafe:
|
|
92
|
+
ctx.log.info("Add unsafe")
|
|
93
|
+
sources.append("'unsafe-inline'")
|
|
94
|
+
|
|
95
|
+
return "script-src {}".format(" ".join(sources))
|
|
96
|
+
|
|
97
|
+
def get_new_csp_header(self, test_header, headers, updated_csp_script):
|
|
98
|
+
"""
|
|
99
|
+
get_new_csp_header generates a new header object containing
|
|
100
|
+
the updated elements from new_csp_script_directives
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
if updated_csp_script:
|
|
104
|
+
directives = self.get_csp_directives(test_header, headers)
|
|
105
|
+
for index, directive in enumerate(directives):
|
|
106
|
+
if directive.startswith("script-src "):
|
|
107
|
+
directives[index] = updated_csp_script
|
|
108
|
+
|
|
109
|
+
ctx.log.info("Original Header %s \n" % headers["Content-Security-Policy"])
|
|
110
|
+
headers["Content-Security-Policy"] = "; ".join(directives)
|
|
111
|
+
ctx.log.info("Updated Header %s \n" % headers["Content-Security-Policy"])
|
|
112
|
+
|
|
113
|
+
return headers
|
|
114
|
+
|
|
115
|
+
def response(self, flow):
|
|
116
|
+
# pylint: disable=W1633
|
|
117
|
+
if "content-type" in flow.response.headers:
|
|
118
|
+
if "text/html" in flow.response.headers["content-type"]:
|
|
119
|
+
ctx.log.info(
|
|
120
|
+
"Working on {}".format(flow.response.headers["content-type"])
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
flow.response.decode()
|
|
124
|
+
html = flow.response.text
|
|
125
|
+
|
|
126
|
+
with open(
|
|
127
|
+
path.join(path.dirname(__file__), "catapult/deterministic.js")
|
|
128
|
+
) as jsfile:
|
|
129
|
+
js = jsfile.read().replace(
|
|
130
|
+
"REPLACE_LOAD_TIMESTAMP", str(self.millis)
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
if js not in html:
|
|
134
|
+
script_index = re.search("(?i).*?<head.*?>", html)
|
|
135
|
+
if script_index is None:
|
|
136
|
+
script_index = re.search("(?i).*?<html.*?>", html)
|
|
137
|
+
if script_index is None:
|
|
138
|
+
script_index = re.search("(?i).*?<!doctype html>", html)
|
|
139
|
+
if script_index is None:
|
|
140
|
+
ctx.log.info(
|
|
141
|
+
f"No start tags found in request {flow.request.url}. Skip injecting"
|
|
142
|
+
)
|
|
143
|
+
return
|
|
144
|
+
script_index = script_index.end()
|
|
145
|
+
|
|
146
|
+
nonce = None
|
|
147
|
+
for test_header in [
|
|
148
|
+
"Content-Security-Policy",
|
|
149
|
+
"Content-Security-Policy-Report-Only",
|
|
150
|
+
]:
|
|
151
|
+
if flow.response.headers.get(test_header, False):
|
|
152
|
+
nonce = self.get_nonce_from_headers(
|
|
153
|
+
test_header, flow.response.headers
|
|
154
|
+
)
|
|
155
|
+
ctx.log.info("nonce : %s" % nonce)
|
|
156
|
+
|
|
157
|
+
if (
|
|
158
|
+
self.get_csp_script_sources(
|
|
159
|
+
test_header, flow.response.headers
|
|
160
|
+
)
|
|
161
|
+
and not nonce
|
|
162
|
+
):
|
|
163
|
+
# generate sha256 for the script
|
|
164
|
+
hash_object = hashlib.sha256(js.encode("utf-8"))
|
|
165
|
+
script_sha256 = base64.b64encode(
|
|
166
|
+
hash_object.digest()
|
|
167
|
+
).decode("utf-8")
|
|
168
|
+
|
|
169
|
+
# generate the new response headers
|
|
170
|
+
updated_script_sources = self.update_csp_script_src(
|
|
171
|
+
test_header,
|
|
172
|
+
flow.response.headers,
|
|
173
|
+
script_sha256,
|
|
174
|
+
)
|
|
175
|
+
flow.response.headers = self.get_new_csp_header(
|
|
176
|
+
test_header,
|
|
177
|
+
flow.response.headers,
|
|
178
|
+
updated_script_sources,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
# generate new html file
|
|
182
|
+
new_html = (
|
|
183
|
+
html[:script_index]
|
|
184
|
+
+ self.get_script_with_nonce(js, nonce)
|
|
185
|
+
+ html[script_index:]
|
|
186
|
+
)
|
|
187
|
+
flow.response.text = new_html
|
|
188
|
+
|
|
189
|
+
ctx.log.info(
|
|
190
|
+
f"In request {flow.request.url} injected deterministic JS"
|
|
191
|
+
)
|
|
192
|
+
else:
|
|
193
|
+
ctx.log.info(
|
|
194
|
+
f"Script already injected in request {flow.request.url}"
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
addons = [AddDeterministic()]
|
mozproxy/driver.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
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
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import signal
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
import mozinfo
|
|
10
|
+
import mozlog.commandline
|
|
11
|
+
|
|
12
|
+
from . import get_playback
|
|
13
|
+
from .utils import LOG, TOOLTOOL_PATHS
|
|
14
|
+
|
|
15
|
+
EXIT_SUCCESS = 0
|
|
16
|
+
EXIT_EARLY_TERMINATE = 3
|
|
17
|
+
EXIT_EXCEPTION = 4
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main():
|
|
21
|
+
parser = argparse.ArgumentParser()
|
|
22
|
+
parser.add_argument(
|
|
23
|
+
"--mode",
|
|
24
|
+
default="playback",
|
|
25
|
+
choices=["record", "playback"],
|
|
26
|
+
help="Proxy server mode. Use `playback` to replay from the provided file(s). "
|
|
27
|
+
"Use `record` to generate a new recording at the path specified by `--file`. "
|
|
28
|
+
"playback - replay from provided file. "
|
|
29
|
+
"record - generate a new recording at the specified path.",
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"file",
|
|
33
|
+
nargs="+",
|
|
34
|
+
help="The playback files to replay, or the file that a recording will be saved to. "
|
|
35
|
+
"For playback, it can be any combination of the following: zip file, manifest file, "
|
|
36
|
+
"or a URL to zip/manifest file. "
|
|
37
|
+
"For recording, it's a zip fle.",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--host", default="localhost", help="The host to use for the proxy server."
|
|
41
|
+
)
|
|
42
|
+
parser.add_argument(
|
|
43
|
+
"--tool",
|
|
44
|
+
default="mitmproxy",
|
|
45
|
+
help="The playback tool to use (default: %(default)s).",
|
|
46
|
+
)
|
|
47
|
+
parser.add_argument(
|
|
48
|
+
"--tool-version",
|
|
49
|
+
default="12.2.1",
|
|
50
|
+
help="The playback tool version to use (default: %(default)s)",
|
|
51
|
+
)
|
|
52
|
+
parser.add_argument(
|
|
53
|
+
"--app", default="firefox", help="The app being tested (default: %(default)s)."
|
|
54
|
+
)
|
|
55
|
+
parser.add_argument(
|
|
56
|
+
"--binary",
|
|
57
|
+
required=True,
|
|
58
|
+
help=("The path to the binary being tested (typically firefox)."),
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument(
|
|
61
|
+
"--topsrcdir",
|
|
62
|
+
required=True,
|
|
63
|
+
help="The top of the source directory for this project.",
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--objdir", required=True, help="The object directory for this build."
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--profiledir", default=None, help="Path to the profile directory."
|
|
70
|
+
)
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
"--local",
|
|
73
|
+
action="store_true",
|
|
74
|
+
help="Run this locally (i.e. not in production).",
|
|
75
|
+
)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--verbose",
|
|
78
|
+
action="store_true",
|
|
79
|
+
default=False,
|
|
80
|
+
help="Run this locally (i.e. not in production).",
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--deterministic",
|
|
84
|
+
action="store_true",
|
|
85
|
+
default=False,
|
|
86
|
+
help="Enable or disable inject_deterministic script when recording.",
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
mozlog.commandline.add_logging_group(parser)
|
|
90
|
+
|
|
91
|
+
args = parser.parse_args()
|
|
92
|
+
mozlog.commandline.setup_logging("mozproxy", args, {"raw": sys.stdout})
|
|
93
|
+
|
|
94
|
+
TOOLTOOL_PATHS.append(
|
|
95
|
+
os.path.join(
|
|
96
|
+
args.topsrcdir, "python", "mozbuild", "mozbuild", "action", "tooltool.py"
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
if hasattr(signal, "SIGBREAK"):
|
|
101
|
+
# Terminating on windows is slightly different than other platforms.
|
|
102
|
+
# On POSIX, we just let Python's default SIGINT handler raise a
|
|
103
|
+
# KeyboardInterrupt. This doesn't work on Windows, so instead we wait
|
|
104
|
+
# for a Ctrl+Break event and raise our own KeyboardInterrupt.
|
|
105
|
+
def handle_sigbreak(sig, frame):
|
|
106
|
+
raise KeyboardInterrupt()
|
|
107
|
+
|
|
108
|
+
signal.signal(signal.SIGBREAK, handle_sigbreak)
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
if args.mode == "playback":
|
|
112
|
+
if len(args.file) == 0:
|
|
113
|
+
raise Exception("Please provide at least one recording file!")
|
|
114
|
+
|
|
115
|
+
# Playback mode
|
|
116
|
+
proxy_service = get_playback({
|
|
117
|
+
"run_local": args.local,
|
|
118
|
+
"host": args.host,
|
|
119
|
+
"binary": args.binary,
|
|
120
|
+
"obj_path": args.objdir,
|
|
121
|
+
"platform": mozinfo.os,
|
|
122
|
+
"playback_tool": args.tool,
|
|
123
|
+
"playback_version": args.tool_version,
|
|
124
|
+
"playback_files": args.file,
|
|
125
|
+
"app": args.app,
|
|
126
|
+
"local_profile_dir": args.profiledir,
|
|
127
|
+
"verbose": args.verbose,
|
|
128
|
+
})
|
|
129
|
+
if args.mode == "record":
|
|
130
|
+
# Record mode
|
|
131
|
+
if len(args.file) > 1:
|
|
132
|
+
raise Exception("Please provide only one recording file!")
|
|
133
|
+
|
|
134
|
+
LOG.info("Recording will be saved to: %s" % args.file)
|
|
135
|
+
proxy_service = get_playback({
|
|
136
|
+
"run_local": args.local,
|
|
137
|
+
"host": args.host,
|
|
138
|
+
"binary": args.binary,
|
|
139
|
+
"obj_path": args.objdir,
|
|
140
|
+
"platform": mozinfo.os,
|
|
141
|
+
"playback_tool": args.tool,
|
|
142
|
+
# bug 1883701 linux uses a different version for now
|
|
143
|
+
"playback_version": ("8.1.1" if mozinfo.isLinux else args.tool_version),
|
|
144
|
+
"record": True,
|
|
145
|
+
"recording_file": args.file[0],
|
|
146
|
+
"app": args.app,
|
|
147
|
+
"local_profile_dir": args.profiledir,
|
|
148
|
+
"verbose": args.verbose,
|
|
149
|
+
"inject_deterministic": args.deterministic,
|
|
150
|
+
})
|
|
151
|
+
LOG.info("Proxy settings %s" % proxy_service)
|
|
152
|
+
proxy_service.start()
|
|
153
|
+
LOG.info("Proxy running on port %d" % proxy_service.port)
|
|
154
|
+
# Wait for a keyboard interrupt from the caller so we know when to
|
|
155
|
+
# terminate.
|
|
156
|
+
proxy_service.wait()
|
|
157
|
+
return EXIT_EARLY_TERMINATE
|
|
158
|
+
except KeyboardInterrupt:
|
|
159
|
+
LOG.info("Terminating mozproxy")
|
|
160
|
+
proxy_service.stop()
|
|
161
|
+
return EXIT_SUCCESS
|
|
162
|
+
except Exception as e:
|
|
163
|
+
LOG.error(str(e), exc_info=True)
|
|
164
|
+
return EXIT_EXCEPTION
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
if __name__ == "__main__":
|
|
168
|
+
main()
|
mozproxy/recordings.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
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
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from shutil import copyfile
|
|
9
|
+
from zipfile import ZipFile
|
|
10
|
+
|
|
11
|
+
from .utils import LOG
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RecordingFile:
|
|
15
|
+
def __init__(self, path_to_zip_file):
|
|
16
|
+
self._recording_zip_path = path_to_zip_file
|
|
17
|
+
|
|
18
|
+
self._base_name = os.path.splitext(os.path.basename(self._recording_zip_path))[
|
|
19
|
+
0
|
|
20
|
+
]
|
|
21
|
+
if not os.path.splitext(path_to_zip_file)[1] == ".zip":
|
|
22
|
+
LOG.error(
|
|
23
|
+
"Wrong file type! The provided recording should be a zip file. %s"
|
|
24
|
+
% path_to_zip_file
|
|
25
|
+
)
|
|
26
|
+
raise Exception(
|
|
27
|
+
"Wrong file type! The provided recording should be a zip file."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# create a temp dir
|
|
31
|
+
self._mozproxy_dir = os.environ["MOZPROXY_DIR"]
|
|
32
|
+
self._tempdir = os.path.join(self._mozproxy_dir, self._base_name)
|
|
33
|
+
|
|
34
|
+
if os.path.exists(self._tempdir):
|
|
35
|
+
LOG.info(
|
|
36
|
+
"The recording dir already exists! Resetting the existing dir and data."
|
|
37
|
+
)
|
|
38
|
+
shutil.rmtree(self._tempdir)
|
|
39
|
+
os.mkdir(self._tempdir)
|
|
40
|
+
|
|
41
|
+
self._metadata_path = self._get_temp_path("metadata.json")
|
|
42
|
+
self._recording = self._get_temp_path("dump.mp")
|
|
43
|
+
|
|
44
|
+
if os.path.exists(path_to_zip_file):
|
|
45
|
+
with ZipFile(path_to_zip_file, "r") as zipObj:
|
|
46
|
+
# Extract all the contents of zip file in different directory
|
|
47
|
+
zipObj.extractall(self._tempdir)
|
|
48
|
+
|
|
49
|
+
if not os.path.exists(self._recording):
|
|
50
|
+
self._convert_to_new_format()
|
|
51
|
+
|
|
52
|
+
if not os.path.exists(self._metadata_path):
|
|
53
|
+
LOG.error("metadata file is missing!")
|
|
54
|
+
raise Exception("metadata file is missing!")
|
|
55
|
+
|
|
56
|
+
with open(self._metadata_path) as json_file:
|
|
57
|
+
self._metadata = json.load(json_file)
|
|
58
|
+
self.validate_recording()
|
|
59
|
+
LOG.info(
|
|
60
|
+
"Loaded recoording generated on %s" % self.metadata("recording_date")
|
|
61
|
+
)
|
|
62
|
+
else:
|
|
63
|
+
LOG.info("Recording file does not exists!!! Generating base structure")
|
|
64
|
+
self._metadata = {"content": [], "recording_date": str(datetime.now())}
|
|
65
|
+
|
|
66
|
+
def _convert_to_new_format(self):
|
|
67
|
+
# Convert zip recording to new format
|
|
68
|
+
|
|
69
|
+
LOG.info("Convert zip recording to new format")
|
|
70
|
+
|
|
71
|
+
for tmp_file in os.listdir(self._tempdir):
|
|
72
|
+
if tmp_file.endswith(".mp"):
|
|
73
|
+
LOG.info("Renaming %s to dump.mp file" % tmp_file)
|
|
74
|
+
os.rename(self._get_temp_path(tmp_file), self._get_temp_path("dump.mp"))
|
|
75
|
+
elif tmp_file.endswith(".json"):
|
|
76
|
+
if tmp_file.startswith("mitm_netlocs_"):
|
|
77
|
+
LOG.info("Renaming %s to netlocs.json file" % tmp_file)
|
|
78
|
+
os.rename(
|
|
79
|
+
self._get_temp_path("%s.json" % os.path.splitext(tmp_file)[0]),
|
|
80
|
+
self._get_temp_path("netlocs.json"),
|
|
81
|
+
)
|
|
82
|
+
else:
|
|
83
|
+
LOG.info("Renaming %s to metadata.json file" % tmp_file)
|
|
84
|
+
os.rename(
|
|
85
|
+
self._get_temp_path("%s.json" % os.path.splitext(tmp_file)[0]),
|
|
86
|
+
self._get_temp_path("metadata.json"),
|
|
87
|
+
)
|
|
88
|
+
elif tmp_file.endswith(".png"):
|
|
89
|
+
LOG.info("Renaming %s to screenshot.png file" % tmp_file)
|
|
90
|
+
os.rename(
|
|
91
|
+
self._get_temp_path("%s.png" % os.path.splitext(tmp_file)[0]),
|
|
92
|
+
self._get_temp_path("screenshot.png"),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def _get_temp_path(self, file_name):
|
|
96
|
+
return os.path.join(self._tempdir, file_name)
|
|
97
|
+
|
|
98
|
+
def validate_recording(self):
|
|
99
|
+
# Validates that minimum zip file content exists
|
|
100
|
+
if not os.path.exists(self._recording):
|
|
101
|
+
LOG.error("Recording file is missing!")
|
|
102
|
+
raise Exception("Recording file is missing!")
|
|
103
|
+
|
|
104
|
+
if not os.path.exists(self._metadata_path):
|
|
105
|
+
LOG.error("Metadata file is missing!")
|
|
106
|
+
raise Exception("Metadata file is missing!")
|
|
107
|
+
|
|
108
|
+
if "content" in self._metadata:
|
|
109
|
+
# check that all extra files specified in the recording are present
|
|
110
|
+
for content_file in self._metadata["content"]:
|
|
111
|
+
if not os.path.exists(self._get_temp_path(content_file)):
|
|
112
|
+
LOG.error("File %s does not exist!!" % content_file)
|
|
113
|
+
raise Exception("Recording file is missing!")
|
|
114
|
+
else:
|
|
115
|
+
LOG.info("Old file type! Not confirming content!")
|
|
116
|
+
|
|
117
|
+
def metadata(self, name):
|
|
118
|
+
# Return metadata value
|
|
119
|
+
return self._metadata[name]
|
|
120
|
+
|
|
121
|
+
def set_metadata(self, entry, value):
|
|
122
|
+
# Set metadata value
|
|
123
|
+
self._metadata[entry] = value
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def recording_path(self):
|
|
127
|
+
# Returns the path of the recoring.mp file included in the zip
|
|
128
|
+
return self._recording
|
|
129
|
+
|
|
130
|
+
def get_file(self, file_name):
|
|
131
|
+
# Returns the path to a specified file included in the recording zip
|
|
132
|
+
return self._get_temp_path(file_name)
|
|
133
|
+
|
|
134
|
+
def add_file(self, path):
|
|
135
|
+
# Adds file to Zip
|
|
136
|
+
if os.path.exists(path):
|
|
137
|
+
copyfile(path, self._tempdir)
|
|
138
|
+
self._metadata["content"].append(os.path.basename(path))
|
|
139
|
+
else:
|
|
140
|
+
LOG.error("Target file %s does not exist!!" % path)
|
|
141
|
+
raise Exception("File does not exist!!!")
|
|
142
|
+
|
|
143
|
+
def update_metadata(self):
|
|
144
|
+
# Update metadata with information generated by HttpProtocolExtractor plugin
|
|
145
|
+
# This data is geerated after closing the MitMPtoxy process
|
|
146
|
+
|
|
147
|
+
dump_file = self._get_temp_path("dump.json")
|
|
148
|
+
if os.path.exists(dump_file):
|
|
149
|
+
with open(dump_file) as dump:
|
|
150
|
+
dump_info = json.load(dump)
|
|
151
|
+
self._metadata.update(dump_info)
|
|
152
|
+
|
|
153
|
+
def generate_zip_file(self):
|
|
154
|
+
self.update_metadata()
|
|
155
|
+
with open(self._get_temp_path(self._metadata_path), "w") as metadata_file:
|
|
156
|
+
json.dump(self._metadata, metadata_file, sort_keys=True, indent=4)
|
|
157
|
+
|
|
158
|
+
with ZipFile(self._recording_zip_path, "w") as zf:
|
|
159
|
+
zf.write(self._metadata_path, "metadata.json")
|
|
160
|
+
zf.write(self.recording_path, "dump.mp")
|
|
161
|
+
for file in self._metadata["content"]:
|
|
162
|
+
zf.write(self._get_temp_path(file), file)
|
|
163
|
+
LOG.info("Generated new recording file at: %s" % self._recording_zip_path)
|
mozproxy/server.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
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
|
+
from mozproxy.backends.mitm.android import MitmproxyAndroid
|
|
6
|
+
from mozproxy.backends.mitm.desktop import MitmproxyDesktop
|
|
7
|
+
from mozproxy.utils import LOG
|
|
8
|
+
|
|
9
|
+
_BACKENDS = {"mitmproxy": MitmproxyDesktop, "mitmproxy-android": MitmproxyAndroid}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def get_backend(name, *args, **kw):
|
|
13
|
+
"""Returns the class that implements the backend.
|
|
14
|
+
|
|
15
|
+
Raises KeyError in case the backend does not exists.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
# Bug 1883701
|
|
19
|
+
# Our linux desktop platforms are still using ubuntu 18
|
|
20
|
+
# which is not compatible with mitm 11. So for the time being
|
|
21
|
+
# force 8.1.1
|
|
22
|
+
if name == "mitmproxy" and args[0]["platform"] == "linux":
|
|
23
|
+
args[0]["playback_version"] = "8.1.1"
|
|
24
|
+
LOG.info("Forcing mitmproxy version 8.1.1 for linux desktop.")
|
|
25
|
+
|
|
26
|
+
return _BACKENDS[name](*args, **kw)
|