diff --git a/monkey/infection_monkey/utils/windows/users.py b/monkey/infection_monkey/utils/windows/users.py index 6890dc170..8cf128c20 100644 --- a/monkey/infection_monkey/utils/windows/users.py +++ b/monkey/infection_monkey/utils/windows/users.py @@ -2,8 +2,18 @@ import logging import subprocess from infection_monkey.utils.auto_new_user import AutoNewUser +from infection_monkey.utils.environment import is_windows_os from infection_monkey.utils.new_user_error import NewUserError +if is_windows_os(): + import win32api + import win32con + import win32event + import win32process + import win32security + from winsys import _advapi32 + + ACTIVE_NO_NET_USER = "/ACTIVE:NO" WAIT_TIMEOUT_IN_MILLISECONDS = 60 * 1000 @@ -42,10 +52,6 @@ class AutoNewWindowsUser(AutoNewUser): _ = subprocess.check_output(windows_cmds, stderr=subprocess.STDOUT) def __enter__(self): - # Importing these only on windows, as they won't exist on linux. - import win32con - import win32security - try: # Logon as new user: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf # -winbase-logonusera @@ -62,12 +68,6 @@ class AutoNewWindowsUser(AutoNewUser): return self def run_as(self, command): - # Importing these only on windows, as they won't exist on linux. - import win32api - import win32event - import win32process - from winsys import _advapi32 - exit_code = -1 process_handle = None thread_handle = None diff --git a/monkey/tests/unit_tests/infection_monkey/utils/windows/test_windows_users.py b/monkey/tests/unit_tests/infection_monkey/utils/windows/test_windows_users.py new file mode 100644 index 000000000..cb5e0746b --- /dev/null +++ b/monkey/tests/unit_tests/infection_monkey/utils/windows/test_windows_users.py @@ -0,0 +1,41 @@ +import os +import subprocess + +import pytest + +from infection_monkey.utils.windows.users import AutoNewWindowsUser + +TEST_USER = "test_user" + + +@pytest.fixture +def subprocess_check_output_spy(monkeypatch): + def mock_check_output(command, stderr): + mock_check_output.command = command + + mock_check_output.command = "" + + monkeypatch.setattr(subprocess, "check_output", mock_check_output) + + return mock_check_output + + +class StubLogonUser: + def __init__(self): + pass + + def Close(): + return None + + +@pytest.mark.skipif(os.name == "posix", reason="This test only runs on Windows.") +def test_new_user_delete_windows(subprocess_check_output_spy, monkeypatch): + monkeypatch.setattr( + "infection_monkey.utils.windows.users.win32security.LogonUser", + lambda _, __, ___, ____, _____: StubLogonUser, + ) + + with (AutoNewWindowsUser(TEST_USER, "password")): + pass + + assert f"net user {TEST_USER} /delete" in " ".join(subprocess_check_output_spy.command)