From f2527b4d89315810a5c0362737e7862ba239728c Mon Sep 17 00:00:00 2001 From: Ilija Lazoroski Date: Tue, 19 Apr 2022 21:37:24 +0200 Subject: [PATCH] Agent: Change windows removal command --- monkey/infection_monkey/model/__init__.py | 13 +++++++++++-- monkey/infection_monkey/monkey.py | 2 +- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/monkey/infection_monkey/model/__init__.py b/monkey/infection_monkey/model/__init__.py index 3d53b5d86..ce71fb05e 100644 --- a/monkey/infection_monkey/model/__init__.py +++ b/monkey/infection_monkey/model/__init__.py @@ -28,9 +28,18 @@ MONKEY_CMDLINE_DETACHED_WINDOWS = "%s start cmd /c %%(monkey_path)s %s" % ( CMD_PREFIX, MONKEY_ARG, ) +# Time for delay deleting monkey executable +DELAY_SECONDS = 5 +# Command that returns 1 if the process is running and 0 otherwise +CHECK_RUNNING_MONKEY_CMD = 'tasklist /fi "PID eq %(exe_pid)s" ^| find /C "%(exe_pid)s"' +DELETE_FILE_AND_EXIT = "del /f /q %(file_path)s & exit" +# Command that checks for running monkey process 20 times +# If the monkey is running it sleeps for 'delay_seconds' +# If the monkey is not running it deletes the executable and exits the loop DELAY_DELETE_CMD = ( - "cmd /c (for /l %%i in (1,0,2) do (ping -n 60 127.0.0.1 & del /f /q %(file_path)s & " - "if not exist %(file_path)s exit)) > NUL 2>&1 " + f'cmd /c (for /l %%i in (1,1,20) do (for /F "delims=" %%j IN ' + f'(\'{CHECK_RUNNING_MONKEY_CMD}\') DO if "%%j"=="1" (timeout {DELAY_SECONDS}) else ' + f"({DELETE_FILE_AND_EXIT})) ) > NUL 2>&1" ) # Commands used for downloading monkeys diff --git a/monkey/infection_monkey/monkey.py b/monkey/infection_monkey/monkey.py index e3d71a2f1..877147ed4 100644 --- a/monkey/infection_monkey/monkey.py +++ b/monkey/infection_monkey/monkey.py @@ -415,7 +415,7 @@ class InfectionMonkey: startupinfo.dwFlags = CREATE_NEW_CONSOLE | STARTF_USESHOWWINDOW startupinfo.wShowWindow = SW_HIDE subprocess.Popen( - DELAY_DELETE_CMD % {"file_path": sys.executable}, + DELAY_DELETE_CMD % {"file_path": sys.executable, "exe_pid": os.getpid()}, stdin=None, stdout=None, stderr=None,