From 1bb7c0916b29e66f1eeb660aa665cd5d8fea802e Mon Sep 17 00:00:00 2001 From: Karl Hiramoto Date: Fri, 27 Nov 2026 06:16:57 +0000 Subject: [PATCH 1/2] fix(auxiliary/mitmdump): skip stop cleanup when mitmdump is not enabled for task --- modules/auxiliary/Mitmdump.py | 57 +++++++++++------ tests/test_mitmdump.py | 111 ++++++++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+), 17 deletions(-) create mode 100644 tests/test_mitmdump.py diff --git a/modules/auxiliary/Mitmdump.py b/modules/auxiliary/Mitmdump.py index d39e313cc8f..0ce3aa905e7 100644 --- a/modules/auxiliary/Mitmdump.py +++ b/modules/auxiliary/Mitmdump.py @@ -95,6 +95,11 @@ 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 "" + return "mitmdump" in options + + class Mitmdump(Auxiliary): """Module for generating HAR with Mitmdump.""" @@ -106,6 +111,9 @@ def __init__(self): def start(self): """Start mitmdump in a separate thread.""" + if not _is_mitmdump_enabled(self.task): + log.info("Exiting mitmdump. No parameter received.") + return False self.mitmdump_thread = MitmdumpThread(self.task, self.machine) self.mitmdump_thread.start() @@ -125,17 +133,21 @@ def __init__(self, task, machine): self.task = task self.machine = machine self.do_run = True + self._enabled = _is_mitmdump_enabled(task) + self._firewall_enabled = 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(","): + options = getattr(self.task, "options", None) or "" + for option in options.split(","): if option.startswith("netns="): - _key, value = option.split("=") + _key, value = option.split("=", 1) return value return "" @@ -143,26 +155,35 @@ def stop(self): """Set stop mitmdump capture.""" self.do_run = False - log.info("MitmdumpThread.stop task.options %s", self.task.options) + if not self._enabled: + return - 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) + 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) + if self._process_started: + 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. + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + else: + wait_for_pid_exit(pid, 15) + + if self._firewall_enabled: + 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) 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 @@ -179,6 +200,7 @@ def run(self): try: rooter("enable_mitmdump", self.host_iface, self.machine.ip, self.host_port, netns) + self._firewall_enabled = True except subprocess.CalledProcessError as e: log.error("Failed to execute firewall rules: %s", e) @@ -211,6 +233,7 @@ 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) + 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) return diff --git a/tests/test_mitmdump.py b/tests/test_mitmdump.py new file mode 100644 index 00000000000..6211594dea4 --- /dev/null +++ b/tests/test_mitmdump.py @@ -0,0 +1,111 @@ +import logging +import os +import signal +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 TestMitmdumpDisabled: + @pytest.mark.parametrize("options", ["procmemdump=1,route=none", "", None]) + def test_start_and_stop_skip_when_mitmdump_option_absent(self, options, caplog): + with ( + patch.object(mitmdump_mod, "Database", create=True), + 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()) + + 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 caplog.records == [] + + @pytest.mark.parametrize("options", ["procmemdump=1,route=none", "", None]) + def test_thread_stop_does_not_read_pid_or_disable_firewall_when_disabled(self, options, caplog): + with 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 + + with patch.object(mitmdump_mod, "rooter") as mock_rooter, caplog.at_level(logging.ERROR): + thread.run() + thread.stop() + + mock_rooter.assert_not_called() + assert caplog.records == [] + + +class TestMitmdumpEnabled: + def test_stop_skips_pid_read_and_firewall_disable_when_run_did_not_start_process(self, caplog): + with 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", side_effect=mitmdump_mod.subprocess.CalledProcessError(1, "rooter")), + patch.object(mitmdump_mod.subprocess, "Popen", side_effect=OSError("missing binary")), + caplog.at_level(logging.ERROR), + ): + thread.run() + + 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.stop() + + mock_read_pid.assert_not_called() + mock_rooter.assert_not_called() + assert caplog.records == [] + + def test_run_and_stop_kill_pid_and_disable_firewall_when_enabled(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,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) + with ( + patch.object(mitmdump_mod, "rooter") as mock_rooter, + patch.object(mitmdump_mod.subprocess, "Popen", return_value=fake_proc) as mock_popen, + patch.object(mitmdump_mod.os, "kill") as mock_kill, + patch.object(mitmdump_mod, "wait_for_pid_exit", return_value=True) as mock_wait, + ): + thread.run() + thread.stop() + + mock_popen.assert_called_once() + mock_kill.assert_called_once_with(99999, signal.SIGTERM) + mock_wait.assert_called_once_with(99999, 15) + assert mock_rooter.call_args_list[0].args == ("enable_mitmdump", thread.host_iface, "10.0.0.5", "8001", "ns1") + assert mock_rooter.call_args_list[1].args == ("disable_mitmdump", thread.host_iface, "10.0.0.5", "8001", "ns1") From ebc1b16ddc60b64ac3cda2fb7f1986ca337a1dbb Mon Sep 17 00:00:00 2001 From: Karl Hiramoto Date: Fri, 27 Nov 2026 06:31:52 +0000 Subject: [PATCH 2/2] fix(auxiliary/mitmdump): synchronize stop with run, handle rooter dicts, and parse options --- modules/auxiliary/Mitmdump.py | 136 ++++++++++++++++----- tests/test_mitmdump.py | 218 ++++++++++++++++++++++++++++------ 2 files changed, 287 insertions(+), 67 deletions(-) diff --git a/modules/auxiliary/Mitmdump.py b/modules/auxiliary/Mitmdump.py index 0ce3aa905e7..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 @@ -97,7 +98,18 @@ def wait_for_pid_exit(pid, timeout=None, poll_interval=0.01, max_poll_interval=0 def _is_mitmdump_enabled(task) -> bool: options = getattr(task, "options", None) or "" - return "mitmdump" in options + 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): @@ -112,7 +124,7 @@ def __init__(self): def start(self): """Start mitmdump in a separate thread.""" if not _is_mitmdump_enabled(self.task): - log.info("Exiting mitmdump. No parameter received.") + log.debug("Exiting mitmdump. No parameter received.") return False self.mitmdump_thread = MitmdumpThread(self.task, self.machine) @@ -134,7 +146,8 @@ def __init__(self, task, machine): self.machine = machine self.do_run = True self._enabled = _is_mitmdump_enabled(task) - self._firewall_enabled = False + 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") @@ -146,11 +159,57 @@ def __init__(self, task, machine): def _get_netns(self): options = getattr(self.task, "options", None) or "" for option in options.split(","): - if option.startswith("netns="): - _key, value = option.split("=", 1) - return value + token = option.strip() + if token.startswith("netns="): + _key, value = token.split("=", 1) + return value.strip() return "" + def _disable_firewall(self, netns=None): + with self._state_lock: + if not self._firewall_enable_attempted: + return + self._firewall_enable_attempted = False + + 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. + 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 @@ -158,27 +217,18 @@ def stop(self): if not self._enabled: return - log.info("MitmdumpThread.stop task.options %s", self.task.options) + if self.is_alive() and threading.current_thread() is not self: + self.join(timeout=65) - if self._process_started: - 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. - try: - os.kill(pid, signal.SIGTERM) - except ProcessLookupError: - pass - else: - wait_for_pid_exit(pid, 15) + log.info("MitmdumpThread.stop task.options %s", self.task.options) - if self._firewall_enabled: - 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) + try: + 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): @@ -193,17 +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) - self._firewall_enabled = True + 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 @@ -214,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", @@ -233,9 +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) - self._process_started = True + 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 index 6211594dea4..b76773b1877 100644 --- a/tests/test_mitmdump.py +++ b/tests/test_mitmdump.py @@ -1,6 +1,7 @@ import logging import os import signal +import threading from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -17,17 +18,29 @@ def _make_machine(ip="192.168.122.10"): return SimpleNamespace(ip=ip) -class TestMitmdumpDisabled: - @pytest.mark.parametrize("options", ["procmemdump=1,route=none", "", None]) - def test_start_and_stop_skip_when_mitmdump_option_absent(self, options, caplog): - with ( - patch.object(mitmdump_mod, "Database", create=True), - patch.object(mitmdump_mod.Auxiliary, "__init__", return_value=None), - ): +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, @@ -38,55 +51,191 @@ def test_start_and_stop_skip_when_mitmdump_option_absent(self, options, caplog): mock_thread_cls.assert_not_called() mock_rooter.assert_not_called() - assert caplog.records == [] + 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() - @pytest.mark.parametrize("options", ["procmemdump=1,route=none", "", None]) - def test_thread_stop_does_not_read_pid_or_disable_firewall_when_disabled(self, options, caplog): - with patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port") as mock_port: + 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 - with patch.object(mitmdump_mod, "rooter") as mock_rooter, caplog.at_level(logging.ERROR): + 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 caplog.records == [] + 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_read_and_firewall_disable_when_run_did_not_start_process(self, caplog): - with patch.object(mitmdump_mod.MitmdumpThread, "_get_unused_port", return_value="8001"): + 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", side_effect=mitmdump_mod.subprocess.CalledProcessError(1, "rooter")), - patch.object(mitmdump_mod.subprocess, "Popen", side_effect=OSError("missing binary")), - caplog.at_level(logging.ERROR), + 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() - caplog.clear() + 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, - patch.object(mitmdump_mod, "rooter") as mock_rooter, - caplog.at_level(logging.ERROR), ): + thread.run() thread.stop() + mock_popen.assert_not_called() mock_read_pid.assert_not_called() - mock_rooter.assert_not_called() - assert caplog.records == [] + assert [c.args[0] for c in mock_rooter.call_args_list] == ["enable_mitmdump", "disable_mitmdump"] - def test_run_and_stop_kill_pid_and_disable_firewall_when_enabled(self, tmp_path): + 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=42, options="mitmdump=yes,netns=ns1"), + _make_task(task_id=43, options="mitmdump=yes,netns=ns1"), _make_machine("10.0.0.5"), ) @@ -95,17 +244,18 @@ def test_run_and_stop_kill_pid_and_disable_firewall_when_enabled(self, tmp_path) f.write("99999\n") fake_proc = MagicMock(pid=12345) + fake_proc.poll.return_value = 0 with ( - patch.object(mitmdump_mod, "rooter") as mock_rooter, - patch.object(mitmdump_mod.subprocess, "Popen", return_value=fake_proc) as mock_popen, - patch.object(mitmdump_mod.os, "kill") as mock_kill, - patch.object(mitmdump_mod, "wait_for_pid_exit", return_value=True) as mock_wait, + 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_popen.assert_called_once() - mock_kill.assert_called_once_with(99999, signal.SIGTERM) - mock_wait.assert_called_once_with(99999, 15) - assert mock_rooter.call_args_list[0].args == ("enable_mitmdump", thread.host_iface, "10.0.0.5", "8001", "ns1") - assert mock_rooter.call_args_list[1].args == ("disable_mitmdump", thread.host_iface, "10.0.0.5", "8001", "ns1") + 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"), + ]