diff --git a/modules/auxiliary/Mitmdump.py b/modules/auxiliary/Mitmdump.py index d39e313cc8f..12004bdbb83 100644 --- a/modules/auxiliary/Mitmdump.py +++ b/modules/auxiliary/Mitmdump.py @@ -25,11 +25,12 @@ import logging import os -import socket -import time import signal +import socket import subprocess -from threading import Thread +import threading +import time +from threading import Lock, Thread from lib.cuckoo.common.abstracts import Auxiliary from lib.cuckoo.common.config import Config @@ -95,6 +96,22 @@ def wait_for_pid_exit(pid, timeout=None, poll_interval=0.01, max_poll_interval=0 interval = min(interval * 2, max_poll_interval) +def _is_mitmdump_enabled(task) -> bool: + options = getattr(task, "options", None) or "" + enabled = False + for option in options.split(","): + token = option.strip() + if not token: + continue + if "=" in token: + key, val = token.split("=", 1) + if key.strip().lower() == "mitmdump": + enabled = val.strip().lower() not in ("0", "no", "false", "") + elif token.lower() == "mitmdump": + enabled = True + return enabled + + class Mitmdump(Auxiliary): """Module for generating HAR with Mitmdump.""" @@ -106,6 +123,9 @@ def __init__(self): def start(self): """Start mitmdump in a separate thread.""" + if not _is_mitmdump_enabled(self.task): + log.debug("Exiting mitmdump. No parameter received.") + return False self.mitmdump_thread = MitmdumpThread(self.task, self.machine) self.mitmdump_thread.start() @@ -125,44 +145,95 @@ def __init__(self, task, machine): self.task = task self.machine = machine self.do_run = True + self._enabled = _is_mitmdump_enabled(task) + self._state_lock = Lock() + self._firewall_enable_attempted = False + self._process_started = False self.host_ip = mitmdump.cfg.get("host") self.host_iface = mitmdump.cfg.get("interface") self.mitmdump_bin = mitmdump.cfg.get("bin") self.proc = None - self.host_port = self._get_unused_port() + self.host_port = self._get_unused_port() if self._enabled else None self.mitmdump_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(self.task.id), "mitmdump") def _get_netns(self): - for option in self.task.options.split(","): - if option.startswith("netns="): - _key, value = option.split("=") - return value + options = getattr(self.task, "options", None) or "" + for option in options.split(","): + token = option.strip() + if token.startswith("netns="): + _key, value = token.split("=", 1) + return value.strip() return "" - def stop(self): - """Set stop mitmdump capture.""" - self.do_run = False + def _disable_firewall(self, netns=None): + with self._state_lock: + if not self._firewall_enable_attempted: + return + self._firewall_enable_attempted = False - log.info("MitmdumpThread.stop task.options %s", self.task.options) + if netns is None: + netns = self._get_netns() + try: + resp = rooter("disable_mitmdump", self.host_iface, self.machine.ip, self.host_port, netns) + except subprocess.CalledProcessError as e: + log.error("Failed to execute firewall rules: %s", e) + return + if isinstance(resp, dict) and resp.get("exception"): + log.error("Failed to execute firewall rules: %s", resp["exception"]) + def _stop_process(self): pidfile_path = os.path.join(self.mitmdump_path, "mitmdump.pid") pid = read_pid_from_file(pidfile_path) if pid: log.info("MitmdumpThread.stop pid %s", pid) # must directly kill subprocess since popen does sudo. - os.kill(pid, signal.SIGTERM) - wait_for_pid_exit(pid, 15) + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + except OSError as e: + log.error("Failed to terminate mitmdump pid %s: %s", pid, e) + else: + if self.proc is not None and self.proc.pid == pid: + try: + self.proc.wait(timeout=15) + except subprocess.TimeoutExpired: + log.warning("Timed out waiting for mitmdump pid %s to exit", pid) + else: + wait_for_pid_exit(pid, 15) + elif self.proc is not None and self.proc.poll() is None: + self.proc.terminate() + + if self.proc is not None and self.proc.poll() is None: + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + log.warning("Timed out waiting for mitmdump wrapper process %s", self.proc.pid) + + def stop(self): + """Set stop mitmdump capture.""" + self.do_run = False + + if not self._enabled: + return + + if self.is_alive() and threading.current_thread() is not self: + self.join(timeout=65) + + log.info("MitmdumpThread.stop task.options %s", self.task.options) try: - netns = self._get_netns() - rooter("disable_mitmdump", self.host_iface, self.machine.ip, self.host_port, netns) - except subprocess.CalledProcessError as e: - log.error("Failed to execute firewall rules: %s", e) + with self._state_lock: + process_started = self._process_started + if process_started: + self._stop_process() + finally: + self._disable_firewall() log.info("MitmdumpThread.stop finished") def run(self): """Core function to the manage the module""" - if "mitmdump" not in self.task.options: + if not self._enabled: log.info("Exiting mitmdump. No parameter received.") return @@ -172,16 +243,36 @@ def run(self): return if not self.host_port: - log.exception("All ports in range are in use") + log.error("All ports in range are in use") return netns = self._get_netns() + with self._state_lock: + if not self.do_run: + return + self._firewall_enable_attempted = True + try: - rooter("enable_mitmdump", self.host_iface, self.machine.ip, self.host_port, netns) + resp = rooter("enable_mitmdump", self.host_iface, self.machine.ip, self.host_port, netns) except subprocess.CalledProcessError as e: log.error("Failed to execute firewall rules: %s", e) + return + + if isinstance(resp, dict) and resp.get("exception"): + log.error("Failed to execute firewall rules: %s", resp["exception"]) + if resp.get("rooter_unavailable"): + with self._state_lock: + self._firewall_enable_attempted = False + else: + self._disable_firewall(netns) + return + + if not self.do_run: + self._disable_firewall(netns) + return + file_path = os.path.join(self.mitmdump_path, "dump.har") try: mitmdump_args = [] listen_host = self.host_ip @@ -192,7 +283,6 @@ def run(self): mitmdump_args.extend(["/usr/bin/sudo", "ip", "netns", "exec", netns, "/usr/bin/sudo", "-u", "cape"]) os.makedirs(self.mitmdump_path, exist_ok=True) - file_path = os.path.join(self.mitmdump_path, "dump.har") mitmdump_args.extend( [ "/opt/mitmproxy/mitmdump_wrapper.sh", @@ -211,8 +301,11 @@ def run(self): "".join(mitmdump_args[-2:]) ] # concatenate the last two arguments, otherwise the HAR file will not be created. self.proc = subprocess.Popen(mitmdump_args, stdout=None, stderr=None, shell=False, cwd=self.mitmdump_path) + with self._state_lock: + self._process_started = True except (OSError, ValueError): log.exception("Failed to mitmdump (host=%s, port=%s, dump_path=%s)", self.host_ip, self.host_port, file_path) + self._disable_firewall(netns) return log.info( diff --git a/tests/test_mitmdump.py b/tests/test_mitmdump.py new file mode 100644 index 00000000000..b76773b1877 --- /dev/null +++ b/tests/test_mitmdump.py @@ -0,0 +1,261 @@ +import logging +import os +import signal +import threading +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from modules.auxiliary import Mitmdump as mitmdump_mod + + +def _make_task(task_id=23, options="procmemdump=1,route=none"): + return SimpleNamespace(id=task_id, options=options) + + +def _make_machine(ip="192.168.122.10"): + return SimpleNamespace(ip=ip) + + +class TestMitmdumpOptions: + @pytest.mark.parametrize( + "options", + [ + "procmemdump=1,route=none", + "", + None, + "mitmdump=0", + "mitmdump=no", + "mitmdump=false", + "mitmdump=", + "nomitmdump=1", + "referrer=https://example.com/mitmdump", + "mitmdump=1,mitmdump=0", + ], + ) + def test_start_and_stop_skip_when_mitmdump_disabled(self, options, caplog): + with patch.object(mitmdump_mod.Auxiliary, "__init__", return_value=None): + aux = mitmdump_mod.Mitmdump() + aux.set_task(_make_task(options=options)) + aux.set_machine(_make_machine()) + + caplog.clear() + with ( + patch.object(mitmdump_mod, "MitmdumpThread") as mock_thread_cls, + patch.object(mitmdump_mod, "rooter") as mock_rooter, + caplog.at_level(logging.ERROR), + ): + assert aux.start() is False + aux.stop() + + mock_thread_cls.assert_not_called() + mock_rooter.assert_not_called() + assert [r for r in caplog.records if r.levelno >= logging.ERROR] == [] + + @pytest.mark.parametrize("options", ["mitmdump", "mitmdump=yes", "mitmdump=1", "MITMDUMP=1", "procmemdump=1, mitmdump=yes"]) + def test_start_launches_thread_when_mitmdump_enabled(self, options): + with patch.object(mitmdump_mod.Auxiliary, "__init__", return_value=None): + aux = mitmdump_mod.Mitmdump() + aux.set_task(_make_task(options=options)) + aux.set_machine(_make_machine()) + + fake_thread = MagicMock() + with patch.object(mitmdump_mod, "MitmdumpThread", return_value=fake_thread) as mock_thread_cls: + assert aux.start() is True + aux.stop() + + mock_thread_cls.assert_called_once_with(aux.task, aux.machine) + fake_thread.start.assert_called_once_with() + fake_thread.stop.assert_called_once_with() + + @pytest.mark.parametrize("options", ["procmemdump=1,route=none", "", None, "mitmdump=0", "mitmdump=false"]) + def test_thread_stop_does_not_read_pid_or_disable_firewall_when_disabled(self, options, tmp_path, caplog): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port") as mock_port, + ): + thread = mitmdump_mod.MitmdumpThread(_make_task(options=options), _make_machine()) + + mock_port.assert_not_called() + assert thread.host_port is None + + caplog.clear() + with ( + patch.object(mitmdump_mod, "read_pid_from_file") as mock_read_pid, + patch.object(mitmdump_mod, "rooter") as mock_rooter, + caplog.at_level(logging.ERROR), + ): + thread.run() + thread.stop() + + mock_read_pid.assert_not_called() + mock_rooter.assert_not_called() + assert [r for r in caplog.records if r.levelno >= logging.ERROR] == [] + + def test_get_netns_strips_whitespace(self, tmp_path): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"), + ): + thread = mitmdump_mod.MitmdumpThread(_make_task(options="mitmdump=yes, netns=ns1 "), _make_machine()) + + assert thread._get_netns() == "ns1" + + +class TestMitmdumpEnabled: + def test_stop_skips_pid_and_disable_when_rooter_unavailable(self, tmp_path): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"), + ): + thread = mitmdump_mod.MitmdumpThread(_make_task(options="mitmdump=yes"), _make_machine()) + + with ( + patch.object( + mitmdump_mod, + "rooter", + return_value={"output": None, "exception": "rooter is not reachable", "rooter_unavailable": True}, + ) as mock_rooter, + patch.object(mitmdump_mod.subprocess, "Popen") as mock_popen, + patch.object(mitmdump_mod, "read_pid_from_file") as mock_read_pid, + ): + thread.run() + thread.stop() + + mock_popen.assert_not_called() + mock_read_pid.assert_not_called() + mock_rooter.assert_called_once_with("enable_mitmdump", thread.host_iface, "192.168.122.10", "8001", "") + + def test_enable_timeout_rolls_back_firewall_and_skips_popen(self, tmp_path): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"), + ): + thread = mitmdump_mod.MitmdumpThread(_make_task(options="mitmdump=yes"), _make_machine()) + + with ( + patch.object(mitmdump_mod, "rooter", return_value={"output": None, "exception": "timed out"}) as mock_rooter, + patch.object(mitmdump_mod.subprocess, "Popen") as mock_popen, + patch.object(mitmdump_mod, "read_pid_from_file") as mock_read_pid, + ): + thread.run() + thread.stop() + + mock_popen.assert_not_called() + mock_read_pid.assert_not_called() + assert [c.args[0] for c in mock_rooter.call_args_list] == ["enable_mitmdump", "disable_mitmdump"] + + def test_popen_failure_rolls_back_firewall_once_and_skips_pid_read(self, tmp_path): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"), + ): + thread = mitmdump_mod.MitmdumpThread(_make_task(options="mitmdump=yes"), _make_machine()) + + with ( + patch.object(mitmdump_mod, "rooter", return_value={"output": "", "exception": None}) as mock_rooter, + patch.object(mitmdump_mod.subprocess, "Popen", side_effect=OSError("missing binary")), + patch.object(mitmdump_mod, "read_pid_from_file") as mock_read_pid, + ): + thread.run() + thread.stop() + + mock_read_pid.assert_not_called() + assert [c.args[0] for c in mock_rooter.call_args_list] == ["enable_mitmdump", "disable_mitmdump"] + + def test_stop_concurrent_with_enable_mitmdump_joins_skips_popen_and_disables(self, tmp_path): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"), + ): + thread = mitmdump_mod.MitmdumpThread(_make_task(options="mitmdump=yes"), _make_machine()) + + enable_entered = threading.Event() + allow_enable_return = threading.Event() + calls = [] + + def fake_rooter(cmd, *args): + calls.append(cmd) + if cmd == "enable_mitmdump": + enable_entered.set() + assert allow_enable_return.wait(timeout=5) + return {"output": "", "exception": None} + + with ( + patch.object(mitmdump_mod, "rooter", side_effect=fake_rooter), + patch.object(mitmdump_mod.subprocess, "Popen") as mock_popen, + ): + thread.start() + assert enable_entered.wait(timeout=5) + + stopper = threading.Thread(target=thread.stop) + stopper.start() + allow_enable_return.set() + stopper.join(timeout=5) + thread.join(timeout=5) + + mock_popen.assert_not_called() + assert calls == ["enable_mitmdump", "disable_mitmdump"] + + def test_run_and_stop_reaps_direct_process_without_spinning(self, tmp_path): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"), + ): + thread = mitmdump_mod.MitmdumpThread(_make_task(task_id=42, options="mitmdump=yes"), _make_machine("10.0.0.5")) + + os.makedirs(thread.mitmdump_path, exist_ok=True) + with open(os.path.join(thread.mitmdump_path, "mitmdump.pid"), "w") as f: + f.write("12345\n") + + fake_proc = MagicMock(pid=12345) + fake_proc.poll.return_value = 0 + with ( + patch.object(mitmdump_mod, "rooter", return_value={"output": "", "exception": None}) as mock_rooter, + patch.object(mitmdump_mod.subprocess, "Popen", return_value=fake_proc), + patch.object(mitmdump_mod.os, "kill") as mock_kill, + patch.object(mitmdump_mod, "wait_for_pid_exit") as mock_wait, + ): + thread.run() + thread.stop() + + mock_kill.assert_called_once_with(12345, signal.SIGTERM) + fake_proc.wait.assert_called_once_with(timeout=15) + mock_wait.assert_not_called() + assert [c.args for c in mock_rooter.call_args_list] == [ + ("enable_mitmdump", thread.host_iface, "10.0.0.5", "8001", ""), + ("disable_mitmdump", thread.host_iface, "10.0.0.5", "8001", ""), + ] + + @pytest.mark.parametrize("kill_exc", [ProcessLookupError(), PermissionError("operation not permitted")]) + def test_stop_still_disables_firewall_when_kill_fails_in_netns(self, tmp_path, kill_exc): + with ( + patch.object(mitmdump_mod, "CUCKOO_ROOT", str(tmp_path)), + patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"), + ): + thread = mitmdump_mod.MitmdumpThread( + _make_task(task_id=43, options="mitmdump=yes,netns=ns1"), + _make_machine("10.0.0.5"), + ) + + os.makedirs(thread.mitmdump_path, exist_ok=True) + with open(os.path.join(thread.mitmdump_path, "mitmdump.pid"), "w") as f: + f.write("99999\n") + + fake_proc = MagicMock(pid=12345) + fake_proc.poll.return_value = 0 + with ( + patch.object(mitmdump_mod, "rooter", return_value={"output": "", "exception": None}) as mock_rooter, + patch.object(mitmdump_mod.subprocess, "Popen", return_value=fake_proc), + patch.object(mitmdump_mod.os, "kill", side_effect=kill_exc), + patch.object(mitmdump_mod, "wait_for_pid_exit") as mock_wait, + ): + thread.run() + thread.stop() + + mock_wait.assert_not_called() + assert [c.args for c in mock_rooter.call_args_list] == [ + ("enable_mitmdump", thread.host_iface, "10.0.0.5", "8001", "ns1"), + ("disable_mitmdump", thread.host_iface, "10.0.0.5", "8001", "ns1"), + ]