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.
Files changed (51) hide show
  1. mozproxy/__init__.py +44 -0
  2. mozproxy/__main__.py +10 -0
  3. mozproxy/backends/__init__.py +3 -0
  4. mozproxy/backends/base.py +29 -0
  5. mozproxy/backends/mitm/__init__.py +6 -0
  6. mozproxy/backends/mitm/android.py +245 -0
  7. mozproxy/backends/mitm/desktop.py +161 -0
  8. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-linux64.manifest +10 -0
  9. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-osx-arm64.manifest +10 -0
  10. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-osx.manifest +10 -0
  11. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-11.0.0-win.manifest +10 -0
  12. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-linux64.manifest +10 -0
  13. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-osx-arm64.manifest +10 -0
  14. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-osx.manifest +10 -0
  15. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-12.2.1-win.manifest +10 -0
  16. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-linux64.manifest +10 -0
  17. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-osx.manifest +10 -0
  18. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-4.0.4-win.manifest +10 -0
  19. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-linux64.manifest +10 -0
  20. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-osx.manifest +10 -0
  21. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.0.1-win.manifest +10 -0
  22. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-linux64.manifest +10 -0
  23. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-osx.manifest +10 -0
  24. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-5.1.1-win.manifest +10 -0
  25. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-linux64.manifest +10 -0
  26. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-osx.manifest +10 -0
  27. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-6.0.2-win.manifest +10 -0
  28. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-linux64.manifest +10 -0
  29. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-osx.manifest +10 -0
  30. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-7.0.4-win.manifest +10 -0
  31. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-linux64.manifest +10 -0
  32. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-osx.manifest +10 -0
  33. mozproxy/backends/mitm/manifests/mitmproxy-rel-bin-8.1.1-win.manifest +10 -0
  34. mozproxy/backends/mitm/mitm.py +507 -0
  35. mozproxy/backends/mitm/mitmproxy_requirements.txt +34 -0
  36. mozproxy/backends/mitm/scripts/__init__.py +4 -0
  37. mozproxy/backends/mitm/scripts/alt-serverplayback.py +262 -0
  38. mozproxy/backends/mitm/scripts/alternate-server-replay.py +310 -0
  39. mozproxy/backends/mitm/scripts/catapult/LICENSE +27 -0
  40. mozproxy/backends/mitm/scripts/catapult/deterministic.js +71 -0
  41. mozproxy/backends/mitm/scripts/http_protocol_extractor.py +83 -0
  42. mozproxy/backends/mitm/scripts/inject-deterministic.py +198 -0
  43. mozproxy/driver.py +168 -0
  44. mozproxy/recordings.py +163 -0
  45. mozproxy/server.py +26 -0
  46. mozproxy/utils.py +257 -0
  47. mozproxy-1.0.dist-info/METADATA +33 -0
  48. mozproxy-1.0.dist-info/RECORD +51 -0
  49. mozproxy-1.0.dist-info/WHEEL +5 -0
  50. mozproxy-1.0.dist-info/entry_points.txt +2 -0
  51. mozproxy-1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "size": 24989250,
4
+ "visibility": "public",
5
+ "digest": "75ea9d024cc9138e5bc993c292ec65c2a40ce4e382f01c41ef865ddfac6f1553ee0e73e3ff2003234d6ecab2d3cdbbd38809cc7e62bbcabaed521a623575e2b8",
6
+ "algorithm": "sha512",
7
+ "filename": "mitmproxy-5.1.1-linux.tar.gz",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "size": 13178683,
4
+ "visibility": "public",
5
+ "digest": "efbc90674a85165e9065e70a8f0c2d4e42688a045130546c2d5721cdb4c54637f7d2b9f4e6a6953a37f94d0edb5bf128c25d7a628246a75d4ad7ba6c884589a9",
6
+ "algorithm": "sha512",
7
+ "filename": "mitmproxy-5.1.1-osx.tar.gz",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "size": 18019253,
4
+ "visibility": "public",
5
+ "digest": "69470f6a58c50912072ab6a911ac3e266d5ec8c9410c8aa4bad76cd7f61bca640e748fd682379ef1523f12da2a8c7a9c67d5bbae5f6d6fa164c2c6b9765b79c1",
6
+ "algorithm": "sha512",
7
+ "filename": "mitmproxy-5.1.1-windows.zip",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-6.0.2-linux.tar.gz",
4
+ "size": 73691215,
5
+ "algorithm": "sha512",
6
+ "digest": "e7cbcdee1eda9f7c9ea9b6c811930a7b21403f52b24a1f14030a69a4ee62dd6bf9fa5a0a9f8acc44830803da27b856f0900a09fd560b32384ab2c0e78a1d08ad",
7
+ "visibility": "public",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-6.0.2-osx.tar.gz",
4
+ "size": 40867811,
5
+ "algorithm": "sha512",
6
+ "digest": "f162e89073eb73f7cfe458d54157e31e9e6bb7ae42c262e4070d23949888630015c896de8870958e83ad9360fce6758f01813ce581cb1a3c1a8b436109d2f28d",
7
+ "visibility": "public",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-6.0.2-windows.zip",
4
+ "size": 36482912,
5
+ "algorithm": "sha512",
6
+ "digest": "242701b5090fe71526ac887843ca08a674a5b1261c21f9f8cb86d143b16b4bc50fca80b016b140a4c0fd2c6ec5819aee1e145a57b000a293fe290ba1b21bac9f",
7
+ "visibility": "public",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-7.0.4-linux.tar.gz",
4
+ "size": 76230418,
5
+ "algorithm": "sha512",
6
+ "digest": "fe572230ecb512dc4a162804bd36b6535ea9f85ac8f40ebb076fe0a6d4eb03c3fed1a85bc6f56de964218059961bec46ddf502d7da025c2744e66d0acd597852",
7
+ "visibility": "public",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-7.0.4-osx.tar.gz",
4
+ "size": 42334827,
5
+ "algorithm": "sha512",
6
+ "digest": "d9302399b9c6ac65bea0913aa0830d46c3b09e7c1ddc4bbfd375387b58f5fefaa72550656ae936137ad4ed841a327e889a0f4ee72e548427665615097d20d467",
7
+ "visibility": "public",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-7.0.4-windows.zip",
4
+ "size": 55150536,
5
+ "algorithm": "sha512",
6
+ "digest": "fb89dc5f0781f56741d4e288bef62f7c9b301d96a9258fef7ea467d51b1533f2caa13fe9ac382eaf69770d40399336dca004506f7d55db86afd053e7432e85ae",
7
+ "visibility": "public",
8
+ "unpack": true
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-8.1.1-linux.tar.gz",
4
+ "size": 90353267,
5
+ "algorithm": "sha512",
6
+ "digest": "d6d99dca35dc5797549e58f872067ba6a1bff9903db880eabb9993a224e35fba26a001c0665ce7a9983f1b2212aa9c83646a58e6000c5415aea731fa1fe7f46d",
7
+ "unpack": true,
8
+ "visibility": "public"
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-8.1.1-osx.tar.gz",
4
+ "size": 45230764,
5
+ "algorithm": "sha512",
6
+ "digest": "5ce3893a295c211a05d106f434fa6876dc9d32777c5d6bf1c04aff6ca530fe2dae2140db28b974917c92a4d42892591cf734f6c564ad8ff9ed6093e5d90ee737",
7
+ "unpack": true,
8
+ "visibility": "public"
9
+ }
10
+ ]
@@ -0,0 +1,10 @@
1
+ [
2
+ {
3
+ "filename": "mitmproxy-8.1.1-windows.zip",
4
+ "size": 58309424,
5
+ "algorithm": "sha512",
6
+ "digest": "9f3e73cc95573c85c3ed9b43f25dee9f07d16ee937a8aaad10a6c445584f3d7e3592bdf312b048baae1b30dc83e1f391ad692b5c35d959423b1e861e85576eab",
7
+ "unpack": true,
8
+ "visibility": "public"
9
+ }
10
+ ]
@@ -0,0 +1,507 @@
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 platform
7
+ import signal
8
+ import socket
9
+ import sys
10
+ import time
11
+
12
+ import mozinfo
13
+ from mozprocess import ProcessHandler
14
+
15
+ from mozproxy.backends.base import Playback
16
+ from mozproxy.recordings import RecordingFile
17
+ from mozproxy.utils import (
18
+ LOG,
19
+ download_file_from_url,
20
+ get_available_port,
21
+ tooltool_download,
22
+ transform_platform,
23
+ )
24
+
25
+ here = os.path.dirname(__file__)
26
+ mitm_folder = os.path.dirname(os.path.realpath(__file__))
27
+
28
+ # maximal allowed runtime of a mitmproxy command
29
+ MITMDUMP_COMMAND_TIMEOUT = 30
30
+
31
+
32
+ class Mitmproxy(Playback):
33
+ def __init__(self, config):
34
+ self.config = config
35
+ # Register signal handlers to cleanup mitmdump on interrupt
36
+ if not self._is_test_environment():
37
+ self._register_signals()
38
+
39
+ self.host = (
40
+ "127.0.0.1" if "localhost" in self.config["host"] else self.config["host"]
41
+ )
42
+ self.port = None
43
+ self.mitmproxy_proc = None
44
+ self.mitmdump_path = None
45
+ self.mitmdump_path_dir = None
46
+ self.record_mode = config.get("record", False)
47
+ self.recording = None
48
+ self.playback_files = []
49
+
50
+ self.browser_path = ""
51
+ if config.get("binary", None):
52
+ self.browser_path = os.path.normpath(config.get("binary"))
53
+
54
+ self.policies_dir = None
55
+ self.ignore_mitmdump_exit_failure = config.get(
56
+ "ignore_mitmdump_exit_failure", False
57
+ )
58
+
59
+ if self.record_mode:
60
+ if "recording_file" not in self.config:
61
+ LOG.error(
62
+ "recording_file value was not provided. Proxy service wont' start "
63
+ )
64
+ raise Exception("Please provide a playback_files list.")
65
+
66
+ if not isinstance(self.config.get("recording_file"), str):
67
+ LOG.error("recording_file argument type is not str!")
68
+ raise Exception("recording_file argument type invalid!")
69
+
70
+ if not os.path.splitext(self.config.get("recording_file"))[1] == ".zip":
71
+ LOG.error(
72
+ "Recording file type (%s) should be a zip. "
73
+ "Please provide a valid file type!"
74
+ % self.config.get("recording_file")
75
+ )
76
+ raise Exception("Recording file type should be a zip")
77
+
78
+ if os.path.exists(self.config.get("recording_file")):
79
+ LOG.error(
80
+ "Recording file (%s) already exists."
81
+ "Please provide a valid file path!"
82
+ % self.config.get("recording_file")
83
+ )
84
+ raise Exception("Recording file already exists.")
85
+
86
+ if self.config.get("playback_files", False):
87
+ LOG.error("Record mode is True and playback_files where provided!")
88
+ raise Exception("playback_files specified during record!")
89
+
90
+ if self.config.get("playback_version") is None:
91
+ LOG.error(
92
+ "mitmproxy was not provided with a 'playback_version' "
93
+ "Please provide a valid playback version"
94
+ )
95
+ raise Exception("playback_version not specified!")
96
+
97
+ # mozproxy_dir is where we will download all mitmproxy required files
98
+ # when running locally it comes from obj_path via mozharness/mach
99
+ if self.config.get("obj_path") is not None:
100
+ self.mozproxy_dir = self.config.get("obj_path")
101
+ self.upload_dir = os.environ.get("MOZ_UPLOAD_DIR", self.mozproxy_dir)
102
+ else:
103
+ # in production it is ../tasks/task_N/build/, in production that dir
104
+ # is not available as an envvar, however MOZ_UPLOAD_DIR is set as
105
+ # ../tasks/task_N/build/blobber_upload_dir so take that and go up 1 level
106
+ self.mozproxy_dir = os.path.dirname(
107
+ os.path.dirname(os.environ["MOZ_UPLOAD_DIR"])
108
+ )
109
+
110
+ # Set the upload dir to the internal storage
111
+ self.upload_dir = os.environ.get("MOZ_INTERNAL_UPLOAD_DIR")
112
+
113
+ self.mozproxy_dir = os.path.join(self.mozproxy_dir, "testing", "mozproxy")
114
+
115
+ LOG.info(
116
+ "mozproxy_dir used for mitmproxy downloads and exe files: %s"
117
+ % self.mozproxy_dir
118
+ )
119
+ # setting up the MOZPROXY_DIR env variable so custom scripts know
120
+ # where to get the data
121
+ os.environ["MOZPROXY_DIR"] = self.mozproxy_dir
122
+
123
+ LOG.info("Playback tool: %s" % self.config["playback_tool"])
124
+ LOG.info("Playback tool version: %s" % self.config["playback_version"])
125
+
126
+ def _is_test_environment(self):
127
+ """Check if running under pytest.
128
+
129
+ Signal handlers are skipped during tests since they call sys.exit()
130
+ which would kill the test runner. Tests also mock processes and send
131
+ signals deliberately for testing.
132
+ """
133
+ return (
134
+ "pytest" in sys.modules or os.environ.get("PYTEST_CURRENT_TEST") is not None
135
+ )
136
+
137
+ def _register_signals(self):
138
+ """Register signal handlers for cleanup.
139
+
140
+ SIGINT: Ctrl+C from terminal
141
+ SIGTERM: kill command
142
+ SIGHUP: terminal closed/SSH disconnected (Unix only)
143
+ """
144
+ signal.signal(signal.SIGINT, self._handle_signal)
145
+ signal.signal(signal.SIGTERM, self._handle_signal)
146
+ if hasattr(signal, "SIGHUP"):
147
+ signal.signal(signal.SIGHUP, self._handle_signal)
148
+
149
+ def _handle_signal(self, sig, frame):
150
+ """Called when one of the signals is received.
151
+ Performs cleanup and exits the program cleanly.
152
+ """
153
+ LOG.info(f"Signal {sig} received. Cleaning up...")
154
+ try:
155
+ self.stop()
156
+ except Exception as e:
157
+ LOG.error(f"Error during cleanup: {e}")
158
+ finally:
159
+ sys.exit(128 + sig)
160
+
161
+ def generate_mitmdump_path(self):
162
+ mitmdump_path_tail = ["mitmdump"]
163
+ if (
164
+ self.config["playback_version"] in ("11.0.0", "12.2.1")
165
+ and sys.platform == "darwin"
166
+ ):
167
+ # For MacOS newer versions have a different folder structure.
168
+ # Prepend this new path
169
+ mitmdump_path_tail = [
170
+ "mitmproxy.app",
171
+ "Contents",
172
+ "MacOS",
173
+ ] + mitmdump_path_tail
174
+
175
+ # mitmproxy is unpacked here
176
+ self.mitmdump_path_dir = os.path.normpath(
177
+ os.path.join(
178
+ self.mozproxy_dir,
179
+ "mitmdump-%s" % self.config["playback_version"],
180
+ )
181
+ )
182
+ self.mitmdump_path = os.path.normpath(
183
+ os.path.join(self.mitmdump_path_dir, *mitmdump_path_tail)
184
+ )
185
+
186
+ def download_mitm_bin(self):
187
+ # Download and setup mitm binaries
188
+
189
+ manifest = os.path.join(
190
+ here,
191
+ "manifests",
192
+ "mitmproxy-rel-bin-%s-{platform}.manifest"
193
+ % self.config["playback_version"],
194
+ )
195
+ transformed_manifest = transform_platform(
196
+ manifest,
197
+ self.config["platform"],
198
+ platform.processor(),
199
+ self.config["playback_version"],
200
+ )
201
+
202
+ # generate the mitmdump_path
203
+ self.generate_mitmdump_path()
204
+
205
+ # Check if mitmproxy bin exists
206
+ if os.path.exists(self.mitmdump_path):
207
+ LOG.info("mitmproxy binary already exists. Skipping download")
208
+ else:
209
+ # Download and unpack mitmproxy binary
210
+ download_path = self.mitmdump_path_dir
211
+ LOG.info("create mitmproxy %s dir" % self.config["playback_version"])
212
+ if not os.path.exists(download_path):
213
+ os.makedirs(download_path)
214
+
215
+ LOG.info("downloading mitmproxy binary")
216
+ tooltool_download(
217
+ transformed_manifest, self.config["run_local"], download_path
218
+ )
219
+
220
+ def download_manifest_file(self, manifest_path):
221
+ # Manifest File
222
+ # we use one pageset for all platforms
223
+ LOG.info("downloading mitmproxy pageset")
224
+
225
+ tooltool_download(manifest_path, self.config["run_local"], self.mozproxy_dir)
226
+
227
+ with open(manifest_path) as manifest_file:
228
+ manifest = json.load(manifest_file)
229
+ for file in manifest:
230
+ zip_path = os.path.join(self.mozproxy_dir, file["filename"])
231
+ LOG.info("Adding %s to recording list" % zip_path)
232
+ self.playback_files.append(RecordingFile(zip_path))
233
+
234
+ def download_playback_files(self):
235
+ # Detect type of file from playback_files and download accordingly
236
+ if "playback_files" not in self.config:
237
+ LOG.error(
238
+ "playback_files value was not provided. Proxy service wont' start "
239
+ )
240
+ raise Exception("Please provide a playback_files list.")
241
+
242
+ if not isinstance(self.config["playback_files"], list):
243
+ LOG.error("playback_files should be a list")
244
+ raise Exception("playback_files should be a list")
245
+
246
+ for playback_file in self.config["playback_files"]:
247
+ if playback_file.startswith("https://") and "mozilla.com" in playback_file:
248
+ # URL provided
249
+ dest = os.path.join(self.mozproxy_dir, os.path.basename(playback_file))
250
+ download_file_from_url(playback_file, self.mozproxy_dir, extract=False)
251
+ # Add Downloaded file to playback_files list
252
+ LOG.info("Adding %s to recording list" % dest)
253
+ self.playback_files.append(RecordingFile(dest))
254
+ continue
255
+
256
+ if not os.path.exists(playback_file):
257
+ LOG.error(
258
+ "Zip or manifest file path (%s) does not exist. Please provide a valid path!"
259
+ % playback_file
260
+ )
261
+ raise Exception("Zip or manifest file path does not exist")
262
+
263
+ if os.path.splitext(playback_file)[1] == ".zip":
264
+ # zip file path provided
265
+ LOG.info("Adding %s to recording list" % playback_file)
266
+ self.playback_files.append(RecordingFile(playback_file))
267
+ elif os.path.splitext(playback_file)[1] == ".manifest":
268
+ # manifest file path provided
269
+ self.download_manifest_file(playback_file)
270
+
271
+ def download(self):
272
+ """Download and unpack mitmproxy binary and pageset using tooltool"""
273
+ if not os.path.exists(self.mozproxy_dir):
274
+ os.makedirs(self.mozproxy_dir)
275
+
276
+ self.download_mitm_bin()
277
+
278
+ if self.record_mode:
279
+ self.recording = RecordingFile(self.config["recording_file"])
280
+ else:
281
+ self.download_playback_files()
282
+
283
+ def stop(self):
284
+ LOG.info("Mitmproxy stop!!")
285
+ self.stop_mitmproxy_playback()
286
+ if self.record_mode and self.recording is not None:
287
+ LOG.info("Record mode ON. Generating zip file ")
288
+ self.recording.generate_zip_file()
289
+
290
+ def wait(self, timeout=1):
291
+ """Wait until the mitmproxy process has terminated."""
292
+ # We wait using this method to allow Windows to respond to the Ctrl+Break
293
+ # signal so that we can exit cleanly from the command-line driver.
294
+ while True:
295
+ returncode = self.mitmproxy_proc.wait(timeout)
296
+ if returncode is not None:
297
+ return returncode
298
+
299
+ def start(self):
300
+ # go ahead and download and setup mitmproxy
301
+ self.download()
302
+
303
+ # mitmproxy must be started before setup, so that the CA cert is available
304
+ self.start_mitmproxy(self.mitmdump_path, self.browser_path)
305
+
306
+ # In case the setup fails, we want to stop the process before raising.
307
+ try:
308
+ self.setup()
309
+ except Exception:
310
+ try:
311
+ self.stop()
312
+ except Exception:
313
+ LOG.error("MitmProxy failed to STOP.", exc_info=True)
314
+ LOG.error("Setup of MitmProxy failed.", exc_info=True)
315
+ raise
316
+
317
+ def start_mitmproxy(self, mitmdump_path, browser_path):
318
+ """Startup mitmproxy and replay the specified flow file"""
319
+ if self.mitmproxy_proc is not None:
320
+ raise Exception("Proxy already started.")
321
+ self.port = get_available_port()
322
+
323
+ LOG.info("mitmdump path: %s" % mitmdump_path)
324
+ LOG.info("browser path: %s" % browser_path)
325
+
326
+ # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path
327
+ env = os.environ.copy()
328
+ env["PATH"] = os.path.dirname(browser_path) + os.pathsep + env["PATH"]
329
+ command = [mitmdump_path]
330
+
331
+ if self.config.get("verbose", False):
332
+ # Generate mitmproxy verbose logs
333
+ command.extend(["-v"])
334
+ # add proxy host and port options
335
+ command.extend(["--listen-host", self.host, "--listen-port", str(self.port)])
336
+
337
+ # record mode
338
+ if self.record_mode:
339
+ # generate recording script paths
340
+
341
+ command.extend([
342
+ "--save-stream-file",
343
+ os.path.normpath(self.recording.recording_path),
344
+ "--set",
345
+ "websocket=false",
346
+ ])
347
+ if "inject_deterministic" in self.config.keys():
348
+ command.extend([
349
+ "--scripts",
350
+ os.path.join(mitm_folder, "scripts", "inject-deterministic.py"),
351
+ ])
352
+ self.recording.set_metadata(
353
+ "proxy_version", self.config["playback_version"]
354
+ )
355
+ # playback mode
356
+ elif len(self.playback_files) > 0:
357
+ if self.config["playback_version"] in ["8.1.1", "11.0.0", "12.2.1"]:
358
+ command.extend([
359
+ "--set",
360
+ "websocket=false",
361
+ "--set",
362
+ "connection_strategy=lazy",
363
+ "--set",
364
+ "alt_server_replay_nopop=true",
365
+ "--set",
366
+ "alt_server_replay_kill_extra=true",
367
+ "--set",
368
+ "alt_server_replay_order_reversed=true",
369
+ "--set",
370
+ "tls_version_client_min=TLS1_2",
371
+ "--set",
372
+ "alt_server_replay={}".format(
373
+ ",".join([
374
+ os.path.normpath(playback_file.recording_path)
375
+ for playback_file in self.playback_files
376
+ ])
377
+ ),
378
+ "--scripts",
379
+ os.path.normpath(
380
+ os.path.join(mitm_folder, "scripts", "alt-serverplayback.py")
381
+ ),
382
+ ])
383
+ elif self.config["playback_version"] in [
384
+ "4.0.4",
385
+ "5.1.1",
386
+ "6.0.2",
387
+ ]:
388
+ command.extend([
389
+ "--set",
390
+ "upstream_cert=false",
391
+ "--set",
392
+ "upload_dir=" + os.path.normpath(self.upload_dir),
393
+ "--set",
394
+ "websocket=false",
395
+ "--set",
396
+ "server_replay_files={}".format(
397
+ ",".join([
398
+ os.path.normpath(playback_file.recording_path)
399
+ for playback_file in self.playback_files
400
+ ])
401
+ ),
402
+ "--scripts",
403
+ os.path.normpath(
404
+ os.path.join(
405
+ mitm_folder, "scripts", "alternate-server-replay.py"
406
+ )
407
+ ),
408
+ ])
409
+ else:
410
+ raise Exception("Mitmproxy version is unknown!")
411
+
412
+ else:
413
+ raise Exception(
414
+ "Mitmproxy can't start playback! Playback settings missing."
415
+ )
416
+
417
+ # mitmproxy needs some DLL's that are a part of Firefox itself, so add to path
418
+ env = os.environ.copy()
419
+ if not os.path.dirname(self.browser_path) in env["PATH"]:
420
+ env["PATH"] = os.path.dirname(self.browser_path) + os.pathsep + env["PATH"]
421
+
422
+ LOG.info("Starting mitmproxy playback using env path: %s" % env["PATH"])
423
+ LOG.info("Starting mitmproxy playback using command: %s" % " ".join(command))
424
+ # to turn off mitmproxy log output, use these params for Popen:
425
+ # Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
426
+ self.mitmproxy_proc = ProcessHandler(
427
+ command,
428
+ logfile=os.path.join(self.upload_dir, "mitmproxy.log"),
429
+ env=env,
430
+ storeOutput=False,
431
+ )
432
+ self.mitmproxy_proc.run()
433
+ end_time = time.time() + MITMDUMP_COMMAND_TIMEOUT
434
+
435
+ ready = False
436
+ while time.time() < end_time:
437
+ ready = self.check_proxy(host=self.host, port=self.port)
438
+ if ready:
439
+ LOG.info(
440
+ "Mitmproxy playback successfully started on %s:%d as pid %d"
441
+ % (self.host, self.port, self.mitmproxy_proc.pid)
442
+ )
443
+ return
444
+ time.sleep(0.25)
445
+
446
+ # cannot continue as we won't be able to playback the pages
447
+ LOG.error("Aborting: Mitmproxy process did not startup")
448
+ self.stop_mitmproxy_playback()
449
+ sys.exit(1) # XXX why do we need to do that? a raise is not enough?
450
+
451
+ def stop_mitmproxy_playback(self):
452
+ """Stop the mitproxy server playback"""
453
+ if self.mitmproxy_proc is None or self.mitmproxy_proc.poll() is not None:
454
+ return
455
+ LOG.info(
456
+ "Stopping mitmproxy playback, killing process %d" % self.mitmproxy_proc.pid
457
+ )
458
+ # On Windows, mozprocess brutally kills mitmproxy with TerminateJobObject
459
+ # The process has no chance to gracefully shutdown.
460
+ # Here, we send the process a break event to give it a chance to wrapup.
461
+ # See the signal handler in the alternate-server-replay-4.0.4.py script
462
+ if mozinfo.os == "win":
463
+ LOG.info("Sending CTRL_BREAK_EVENT to mitmproxy")
464
+ os.kill(self.mitmproxy_proc.pid, signal.CTRL_BREAK_EVENT)
465
+ time.sleep(2)
466
+
467
+ exit_code = self.mitmproxy_proc.kill()
468
+ self.mitmproxy_proc = None
469
+
470
+ if exit_code != 0:
471
+ if exit_code is None:
472
+ LOG.error("Failed to kill the mitmproxy playback process")
473
+ return
474
+
475
+ if mozinfo.os == "win":
476
+ from mozprocess.winprocess import ( # noqa
477
+ ERROR_CONTROL_C_EXIT,
478
+ ERROR_CONTROL_C_EXIT_DECIMAL,
479
+ )
480
+
481
+ if exit_code in [ERROR_CONTROL_C_EXIT, ERROR_CONTROL_C_EXIT_DECIMAL]:
482
+ LOG.info(
483
+ "Successfully killed the mitmproxy playback process"
484
+ " with exit code %d" % exit_code
485
+ )
486
+ return
487
+ log_func = LOG.error
488
+ if self.ignore_mitmdump_exit_failure:
489
+ log_func = LOG.info
490
+ log_func("Mitmproxy exited with error code %d" % exit_code)
491
+ else:
492
+ LOG.info("Successfully killed the mitmproxy playback process")
493
+
494
+ def check_proxy(self, host, port):
495
+ """Check that mitmproxy process is working by doing a socket call using the proxy settings
496
+ :param host: Host of the proxy server
497
+ :param port: Port of the proxy server
498
+ :return: True if the proxy service is working
499
+ """
500
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
501
+ try:
502
+ s.connect((host, port))
503
+ s.shutdown(socket.SHUT_RDWR)
504
+ s.close()
505
+ return True
506
+ except OSError:
507
+ return False
@@ -0,0 +1,34 @@
1
+ argh==0.26.2
2
+ asn1crypto==0.22.0
3
+ blinker==1.4
4
+ pycparser==2.17
5
+ cffi==1.10.0
6
+ brotlipy==0.6.0
7
+ certifi==2017.4.17
8
+ click==6.7
9
+ construct==2.8.12
10
+ cryptography==1.8.2
11
+ cssutils==1.0.2
12
+ EditorConfig==0.12.1
13
+ h2==2.6.2
14
+ hpack==3.0.0
15
+ html2text==2016.9.19
16
+ hyperframe==4.0.2
17
+ idna==2.5
18
+ jsbeautifier==1.6.12
19
+ kaitaistruct==0.6
20
+ mitmproxy==4.0.4
21
+ packaging==16.8
22
+ passlib==1.7.1
23
+ pathtools==0.1.2
24
+ pyasn1==0.2.3
25
+ pyOpenSSL==16.2.0
26
+ pyparsing==2.2.0
27
+ pyperclip==1.5.27
28
+ PyYAML==3.12
29
+ requests==2.13.0
30
+ ruamel.yaml==0.13.14
31
+ sortedcontainers==1.5.7
32
+ tornado==4.4.3
33
+ urwid==1.3.1
34
+ watchdog==0.8.3