Merge pull request #1973 from guardicore/1961-decouple-dropper-and-wormconfig

1961 decouple dropper and wormconfig
This commit is contained in:
ilija-lazoroski 2022-06-02 12:00:20 +02:00 committed by GitHub
commit 0baacf3027
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 87 additions and 148 deletions

View File

@ -61,14 +61,6 @@ class Configuration(object):
return result
###########################
# dropper config
###########################
dropper_set_date = True
dropper_date_reference_path_windows = r"%windir%\system32\kernel32.dll"
dropper_date_reference_path_linux = "/bin/sh"
###########################
# monkey config
###########################

View File

@ -7,10 +7,9 @@ import shutil
import subprocess
import sys
import time
from pathlib import WindowsPath
from pathlib import PosixPath, WindowsPath
from common.utils.attack_utils import UsageEnum
from infection_monkey.config import WormConfiguration
from infection_monkey.utils.commands import (
build_monkey_commandline_explicitly,
get_monkey_commandline_linux,
@ -21,8 +20,11 @@ from infection_monkey.utils.file_utils import mark_file_for_deletion_on_windows
if "win32" == sys.platform:
from win32process import DETACHED_PROCESS
DATE_REFERENCE_PATH_WINDOWS = os.path.expandvars(WindowsPath(r"%windir%\system32\kernel32.dll"))
else:
DETACHED_PROCESS = 0
DATE_REFERENCE_PATH_LINUX = PosixPath("/bin/sh")
# Linux doesn't have WindowsError
try:
@ -109,27 +111,23 @@ class MonkeyDrops(object):
return False
if WormConfiguration.dropper_set_date:
if sys.platform == "win32":
dropper_date_reference_path = os.path.expandvars(
WormConfiguration.dropper_date_reference_path_windows
)
else:
dropper_date_reference_path = WormConfiguration.dropper_date_reference_path_linux
if sys.platform == "win32":
dropper_date_reference_path = DATE_REFERENCE_PATH_WINDOWS
else:
dropper_date_reference_path = DATE_REFERENCE_PATH_LINUX
try:
ref_stat = os.stat(dropper_date_reference_path)
except OSError:
logger.warning(
"Cannot set reference date using '%s', file not found",
dropper_date_reference_path,
)
else:
try:
ref_stat = os.stat(dropper_date_reference_path)
os.utime(self._config["destination_path"], (ref_stat.st_atime, ref_stat.st_mtime))
except OSError:
logger.warning(
"Cannot set reference date using '%s', file not found",
dropper_date_reference_path,
)
else:
try:
os.utime(
self._config["destination_path"], (ref_stat.st_atime, ref_stat.st_mtime)
)
except OSError:
logger.warning("Cannot set reference date to destination file")
logger.warning("Cannot set reference date to destination file")
monkey_options = build_monkey_commandline_explicitly(
parent=self.opts.parent,

View File

@ -12,7 +12,7 @@ import string
import requests
from common.common_consts.timeouts import LONG_REQUEST_TIMEOUT
from infection_monkey.exploit.tools.helpers import get_agent_dest_path
from infection_monkey.exploit.tools.helpers import get_agent_dst_path
from infection_monkey.exploit.tools.http_tools import HTTPTools
from infection_monkey.exploit.web_rce import WebRCE
from infection_monkey.model import (
@ -43,7 +43,7 @@ class HadoopExploiter(WebRCE):
return self.exploit_result
try:
monkey_path_on_victim = get_agent_dest_path(self.host, self.options)
monkey_path_on_victim = get_agent_dst_path(self.host)
except KeyError:
return self.exploit_result

View File

@ -12,7 +12,7 @@ from infection_monkey.exploit.log4shell_utils import (
build_exploit_bytecode,
get_log4shell_service_exploiters,
)
from infection_monkey.exploit.tools.helpers import get_agent_dest_path
from infection_monkey.exploit.tools.helpers import get_agent_dst_path
from infection_monkey.exploit.tools.http_tools import HTTPTools
from infection_monkey.exploit.web_rce import WebRCE
from infection_monkey.i_puppet.i_puppet import ExploiterResultData
@ -61,7 +61,7 @@ class Log4ShellExploiter(WebRCE):
self._agent_http_server_thread = None
def _start_servers(self):
target_path = get_agent_dest_path(self.host, self.options)
target_path = get_agent_dst_path(self.host)
# Start http server, to serve agent to victims
agent_http_path = self._start_agent_http_server(target_path)

View File

@ -8,7 +8,7 @@ import pymssql
from common.common_consts.timeouts import LONG_REQUEST_TIMEOUT
from common.utils.exceptions import FailedExploitationError
from infection_monkey.exploit.HostExploiter import HostExploiter
from infection_monkey.exploit.tools.helpers import get_agent_dest_path
from infection_monkey.exploit.tools.helpers import get_agent_dst_path
from infection_monkey.exploit.tools.http_tools import HTTPTools
from infection_monkey.exploit.tools.payload_parsing import LimitedSizePayload
from infection_monkey.i_puppet import ExploiterResultData
@ -59,7 +59,7 @@ class MSSQLExploiter(HostExploiter):
Also, don't forget to start_monkey_server() before self.upload_monkey() and
self.stop_monkey_server() after
"""
monkey_path_on_victim = get_agent_dest_path(self.host, self.options)
monkey_path_on_victim = get_agent_dst_path(self.host)
# Brute force to get connection
creds = generate_identity_secret_pairs(

View File

@ -13,7 +13,7 @@ from infection_monkey.exploit.powershell_utils.powershell_client import (
IPowerShellClient,
PowerShellClient,
)
from infection_monkey.exploit.tools.helpers import get_agent_dest_path, get_random_file_suffix
from infection_monkey.exploit.tools.helpers import get_agent_dst_path, get_random_file_suffix
from infection_monkey.model import DROPPER_ARG, RUN_MONKEY, VictimHost
from infection_monkey.utils.commands import build_monkey_commandline
from infection_monkey.utils.environment import is_windows_os
@ -134,7 +134,7 @@ class PowerShellExploiter(HostExploiter):
raise ValueError(f"Unknown secret type {credentials.secret_type}")
def _execute_monkey_agent_on_victim(self):
monkey_path_on_victim = get_agent_dest_path(self.host, self.options)
monkey_path_on_victim = get_agent_dst_path(self.host)
self._copy_monkey_binary_to_victim(monkey_path_on_victim)
logger.info("Successfully copied the monkey binary to the victim.")

View File

@ -6,7 +6,7 @@ from impacket.dcerpc.v5.scmr import DCERPCSessionError
from common.common_consts.timeouts import LONG_REQUEST_TIMEOUT
from common.utils.attack_utils import ScanStatus, UsageEnum
from infection_monkey.exploit.HostExploiter import HostExploiter
from infection_monkey.exploit.tools.helpers import get_agent_dest_path
from infection_monkey.exploit.tools.helpers import get_agent_dst_path
from infection_monkey.exploit.tools.smb_tools import SmbTools
from infection_monkey.model import DROPPER_CMDLINE_DETACHED_WINDOWS, MONKEY_CMDLINE_DETACHED_WINDOWS
from infection_monkey.telemetry.attack.t1035_telem import T1035Telem
@ -31,7 +31,7 @@ class SMBExploiter(HostExploiter):
def _exploit_host(self):
agent_binary = self.agent_repository.get_agent_binary(self.host.os["type"])
dest_path = get_agent_dest_path(self.host, self.options)
dest_path = get_agent_dst_path(self.host)
creds = generate_brute_force_combinations(self.options["credentials"])
for user, password, lm_hash, ntlm_hash in interruptible_iter(creds, self.interrupt):

View File

@ -9,7 +9,7 @@ from common.utils import Timer
from common.utils.attack_utils import ScanStatus
from common.utils.exceptions import FailedExploitationError
from infection_monkey.exploit.HostExploiter import HostExploiter
from infection_monkey.exploit.tools.helpers import get_agent_dest_path
from infection_monkey.exploit.tools.helpers import get_agent_dst_path
from infection_monkey.i_puppet import ExploiterResultData
from infection_monkey.model import MONKEY_ARG
from infection_monkey.network.tools import check_tcp_port, get_interface_to_target
@ -209,7 +209,7 @@ class SSHExploiter(HostExploiter):
self._set_interrupted()
return self.exploit_result
monkey_path_on_victim = get_agent_dest_path(self.host, self.options)
monkey_path_on_victim = get_agent_dst_path(self.host)
try:
with ssh.open_sftp() as ftp:

View File

@ -2,7 +2,6 @@ import logging
import random
import string
from pathlib import PurePath, PurePosixPath, PureWindowsPath
from typing import Any, Mapping
from infection_monkey.model import VictimHost
@ -10,6 +9,19 @@ logger = logging.getLogger(__name__)
RAND_SUFFIX_LEN = 8
# Where to upload agent binaries on victims
AGENT_BINARY_PATH_LINUX = PurePosixPath("/tmp/monkey")
AGENT_BINARY_PATH_WIN64 = PureWindowsPath(r"C:\Windows\temp\monkey64.exe")
def get_agent_dst_path(host: VictimHost) -> PurePath:
if host.os["type"] == "windows":
path = PureWindowsPath(AGENT_BINARY_PATH_WIN64)
else:
path = PurePosixPath(AGENT_BINARY_PATH_LINUX)
return _add_random_suffix(path)
def get_random_file_suffix() -> str:
character_set = list(string.ascii_letters + string.digits + "_" + "-")
@ -18,15 +30,6 @@ def get_random_file_suffix() -> str:
return random_string
def get_agent_dest_path(host: VictimHost, options: Mapping[str, Any]) -> PurePath:
if host.os["type"] == "windows":
path = PureWindowsPath(options["dropper_target_path_win_64"])
else:
path = PurePosixPath(options["dropper_target_path_linux"])
return _add_random_suffix(path)
# Turns C:\\monkey.exe into C:\\monkey-<random_string>.exe
# Useful to avoid duplicate file paths
def _add_random_suffix(path: PurePath) -> PurePath:

View File

@ -22,7 +22,11 @@ from infection_monkey.model import (
from infection_monkey.network.tools import tcp_port_to_service
from infection_monkey.telemetry.attack.t1197_telem import T1197Telem
from infection_monkey.telemetry.attack.t1222_telem import T1222Telem
from infection_monkey.utils.commands import build_monkey_commandline
from infection_monkey.utils.commands import (
DROPPER_TARGET_PATH_LINUX,
DROPPER_TARGET_PATH_WIN64,
build_monkey_commandline,
)
from infection_monkey.utils.threading import interruptible_iter
logger = logging.getLogger(__name__)
@ -109,8 +113,8 @@ class WebRCE(HostExploiter):
def pre_exploit(self):
if not self.monkey_target_paths:
self.monkey_target_paths = {
"linux": self.options["dropper_target_path_linux"],
"windows": self.options["dropper_target_path_win_64"],
"linux": DROPPER_TARGET_PATH_LINUX,
"windows": DROPPER_TARGET_PATH_WIN64,
}
self.HTTP = [str(port) for port in self.options["http_ports"]]
super().pre_exploit()
@ -405,7 +409,6 @@ class WebRCE(HostExploiter):
"""
Gets default dropper path for the host.
:return: Default monkey's destination path for corresponding host or False if failed.
E.g. config.dropper_target_path_linux(/tmp/monkey.sh) for linux host
"""
if not self.host.os.get("type") or (
self.host.os["type"] != "linux" and self.host.os["type"] != "windows"
@ -413,9 +416,9 @@ class WebRCE(HostExploiter):
logger.error("Target's OS was either unidentified or not supported. Aborting")
return False
if self.host.os["type"] == "linux":
return self.options["dropper_target_path_linux"]
return DROPPER_TARGET_PATH_LINUX
if self.host.os["type"] == "windows":
return self.options["dropper_target_path_win_64"]
return DROPPER_TARGET_PATH_WIN64
def get_target_url(self):
"""

View File

@ -6,7 +6,7 @@ import traceback
from impacket.dcerpc.v5.rpcrt import DCERPCException
from infection_monkey.exploit.HostExploiter import HostExploiter
from infection_monkey.exploit.tools.helpers import get_agent_dest_path
from infection_monkey.exploit.tools.helpers import get_agent_dst_path
from infection_monkey.exploit.tools.smb_tools import SmbTools
from infection_monkey.exploit.tools.wmi_tools import AccessDeniedException, WmiTools
from infection_monkey.i_puppet import ExploiterResultData
@ -15,7 +15,7 @@ from infection_monkey.utils.brute_force import (
generate_brute_force_combinations,
get_credential_string,
)
from infection_monkey.utils.commands import build_monkey_commandline
from infection_monkey.utils.commands import DROPPER_TARGET_PATH_WIN64, build_monkey_commandline
from infection_monkey.utils.threading import interruptible_iter
logger = logging.getLogger(__name__)
@ -74,7 +74,7 @@ class WmiExploiter(HostExploiter):
self._set_interrupted()
return self.exploit_result
target_path = get_agent_dest_path(self.host, self.options)
target_path = get_agent_dst_path(self.host)
remote_full_path = SmbTools.copy_file(
self.host,
@ -91,13 +91,13 @@ class WmiExploiter(HostExploiter):
wmi_connection.close()
return self.exploit_result
# execute the remote dropper in case the path isn't final
elif remote_full_path.lower() != self.options["dropper_target_path_win_64"]:
elif remote_full_path.lower() != DROPPER_TARGET_PATH_WIN64:
cmdline = DROPPER_CMDLINE_WINDOWS % {
"dropper_path": remote_full_path
} + build_monkey_commandline(
self.host,
self.current_depth - 1,
self.options["dropper_target_path_win_64"],
DROPPER_TARGET_PATH_WIN64,
)
else:
cmdline = MONKEY_CMDLINE_WINDOWS % {

View File

@ -1,7 +1,12 @@
from infection_monkey.config import GUID
from infection_monkey.exploit.tools.helpers import AGENT_BINARY_PATH_LINUX, AGENT_BINARY_PATH_WIN64
from infection_monkey.model import CMD_CARRY_OUT, CMD_EXE, MONKEY_ARG
from infection_monkey.model.host import VictimHost
# Dropper target paths
DROPPER_TARGET_PATH_LINUX = AGENT_BINARY_PATH_LINUX
DROPPER_TARGET_PATH_WIN64 = AGENT_BINARY_PATH_WIN64
def build_monkey_commandline(target_host: VictimHost, depth: int, location: str = None) -> str:

View File

@ -617,12 +617,6 @@ class ConfigService:
exploit_options = {}
for dropper_target in [
"dropper_target_path_linux",
"dropper_target_path_win_64",
]:
exploit_options[dropper_target] = config.get(dropper_target, "")
exploit_options["http_ports"] = sorted(config["HTTP_PORTS"])
formatted_exploiters_config = {

View File

@ -135,51 +135,6 @@ INTERNAL = {
}
},
},
"dropper": {
"title": "Dropper",
"type": "object",
"properties": {
"dropper_set_date": {
"title": "Dropper sets date",
"type": "boolean",
"default": True,
"description": "Determines whether the dropper should set the monkey's file "
"date to be the same as"
" another file",
},
"dropper_date_reference_path_windows": {
"title": "Dropper date reference path (Windows)",
"type": "string",
"default": "%windir%\\system32\\kernel32.dll",
"description": "Determines which file the dropper should copy the date from if "
"it's configured to do"
" so on Windows (use fullpath)",
},
"dropper_date_reference_path_linux": {
"title": "Dropper date reference path (Linux)",
"type": "string",
"default": "/bin/sh",
"description": "Determines which file the dropper should copy the date from if "
"it's configured to do"
" so on Linux (use fullpath)",
},
"dropper_target_path_linux": {
"title": "Dropper target path on Linux",
"type": "string",
"default": "/tmp/monkey",
"description": "Determines where should the dropper place the monkey on a "
"Linux machine",
},
"dropper_target_path_win_64": {
"title": "Dropper target path on Windows (64bit)",
"type": "string",
"default": "C:\\Windows\\temp\\monkey64.exe",
"description": "Determines where should the dropper place the monkey on a "
"Windows machine "
"(64 bit)",
},
},
},
"exploits": {
"title": "Exploits",
"type": "object",

View File

@ -69,7 +69,6 @@
"windows_command": ""
},
"depth": 2,
"dropper_set_date": true,
"exploit_lm_hash_list": ["DEADBEEF", "FACADE"],
"exploit_ntlm_hash_list": ["BEADED", "ACCEDE", "DECADE"],
"exploit_password_list": ["p1", "p2", "p3"],

View File

@ -21,11 +21,6 @@
"custom_PBA_linux_cmd": "bash test.sh",
"custom_PBA_windows_cmd": "powershell test.ps1",
"depth": 2,
"dropper_date_reference_path_linux": "/bin/sh",
"dropper_date_reference_path_windows": "%windir%\\system32\\kernel32.dll",
"dropper_set_date": true,
"dropper_target_path_linux": "/tmp/monkey",
"dropper_target_path_win_64": "C:\\Windows\\temp\\monkey64.exe",
"exploit_lm_hash_list": ["lm_hash_1", "lm_hash_2"],
"exploit_ntlm_hash_list": ["nt_hash_1", "nt_hash_2", "nt_hash_3"],
"exploit_password_list": [

View File

@ -96,13 +96,6 @@
"ElasticFinger"
]
},
"dropper": {
"dropper_set_date": true,
"dropper_date_reference_path_windows": "%windir%\\system32\\kernel32.dll",
"dropper_date_reference_path_linux": "/bin/sh",
"dropper_target_path_linux": "/tmp/monkey",
"dropper_target_path_win_64": "C:\\Windows\\temp\\monkey64.exe"
},
"exploits": {
"exploit_lm_hash_list": [],
"exploit_ntlm_hash_list": [],

View File

@ -5,6 +5,7 @@ from unittest.mock import MagicMock
import pytest
from infection_monkey.exploit import powershell
from infection_monkey.exploit.tools.helpers import AGENT_BINARY_PATH_WIN64
from infection_monkey.model.host import VictimHost
# Use the path_win32api_get_user_name fixture for all tests in this module
@ -14,7 +15,6 @@ USER_LIST = ["user1", "user2"]
PASSWORD_LIST = ["pass1", "pass2"]
LM_HASH_LIST = ["bogo_lm_1"]
NT_HASH_LIST = ["bogo_nt_1", "bogo_nt_2"]
DROPPER_TARGET_PATH_64 = "C:\\agent64"
mock_agent_repository = MagicMock()
@ -24,7 +24,6 @@ mock_agent_repository.get_agent_binary.return_value = BytesIO(b"BINARY_EXECUTABL
@pytest.fixture
def powershell_arguments(http_and_https_both_enabled_host):
options = {
"dropper_target_path_win_64": DROPPER_TARGET_PATH_64,
"credentials": {
"exploit_user_list": USER_LIST,
"exploit_password_list": PASSWORD_LIST,
@ -114,7 +113,7 @@ def test_successful_copy(monkeypatch, powershell_exploiter, powershell_arguments
exploit_result = powershell_exploiter.exploit_host(**powershell_arguments)
assert DROPPER_TARGET_PATH_64 in str(mock_client.return_value.copy_file.call_args[0][1])
assert AGENT_BINARY_PATH_WIN64.stem in str(mock_client.return_value.copy_file.call_args[0][1])
assert exploit_result.exploitation_success

View File

@ -2,39 +2,44 @@ from unittest.mock import Mock
import pytest
from infection_monkey.exploit.tools.helpers import RAND_SUFFIX_LEN, get_agent_dest_path
from infection_monkey.exploit.tools.helpers import (
AGENT_BINARY_PATH_LINUX,
AGENT_BINARY_PATH_WIN64,
RAND_SUFFIX_LEN,
get_agent_dst_path,
)
def _get_host_and_options(os, path):
def _get_host(os):
host = Mock()
host.os = {"type": os}
options = {"dropper_target_path_win_64": path, "dropper_target_path_linux": path}
return host, options
return host
@pytest.mark.parametrize("os", ["windows", "linux"])
@pytest.mark.parametrize("path", ["C:\\monkey.exe", "/tmp/monkey-linux-64", "mon.key.exe"])
def test_get_agent_dest_path(os, path):
host, options = _get_host_and_options(os, path)
rand_path = get_agent_dest_path(host, options)
@pytest.mark.parametrize(
"os, path", [("linux", AGENT_BINARY_PATH_LINUX), ("windows", AGENT_BINARY_PATH_WIN64)]
)
def test_get_agent_dst_path(os, path):
host = _get_host(os)
rand_path = get_agent_dst_path(host)
# Assert that filename got longer by RAND_SUFFIX_LEN and one dash
assert len(str(rand_path)) == (len(str(path)) + RAND_SUFFIX_LEN + 1)
def test_get_agent_dest_path_randomness():
host, options = _get_host_and_options("windows", "monkey.exe")
def test_get_agent_dst_path_randomness():
host = _get_host("windows")
path1 = get_agent_dest_path(host, options)
path2 = get_agent_dest_path(host, options)
path1 = get_agent_dst_path(host)
path2 = get_agent_dst_path(host)
assert path1 != path2
def test_get_agent_dest_path_str_place():
host, options = _get_host_and_options("windows", "C:\\abc\\monkey.exe")
def test_get_agent_dst_path_str_place():
host = _get_host("windows")
rand_path = get_agent_dest_path(host, options)
rand_path = get_agent_dst_path(host)
assert str(rand_path).startswith("C:\\abc\\monkey-")
assert str(rand_path).startswith(r"C:\Windows\temp\monkey")
assert str(rand_path).endswith(".exe")

View File

@ -179,8 +179,6 @@ def test_format_config_for_agent__network_scan(flat_monkey_config):
def test_format_config_for_agent__exploiters(flat_monkey_config):
expected_exploiters_config = {
"options": {
"dropper_target_path_linux": "/tmp/monkey",
"dropper_target_path_win_64": r"C:\Windows\temp\monkey64.exe",
"http_ports": [80, 443, 7001, 8008, 8080, 9200],
},
"brute_force": [