示例#1
0
    def initialize(self):
        """
        Set up scanning based on configuration
        FixedRange -> Reads from range_fixed field in configuration
        otherwise, takes a range from every IP address the current host has.
        :return:
        """
        # get local ip addresses
        self._ip_addresses = local_ips()

        if not self._ip_addresses:
            raise Exception("Cannot find local IP address for the machine")

        LOG.info("Found local IP addresses of the machine: %r",
                 self._ip_addresses)
        # for fixed range, only scan once.
        if WormConfiguration.range_class is FixedRange:
            self._ranges = [
                WormConfiguration.range_class(
                    fixed_addresses=WormConfiguration.range_fixed)
            ]
        else:
            self._ranges = [
                WormConfiguration.range_class(ip_address)
                for ip_address in self._ip_addresses
            ]
        if WormConfiguration.local_network_scan:
            self._ranges += [
                FixedRange(
                    [ip_address for ip_address in get_ips_from_interfaces()])
            ]
        LOG.info("Base local networks to scan are: %r", self._ranges)
示例#2
0
    def load_control_config():
        if not WormConfiguration.current_server:
            return
        try:
            reply = requests.get("https://%s/api/monkey/%s" %
                                 (WormConfiguration.current_server, GUID),
                                 verify=False,
                                 proxies=ControlClient.proxies)

        except Exception as exc:
            LOG.warn("Error connecting to control server %s: %s",
                     WormConfiguration.current_server, exc)
            return

        try:
            unknown_variables = WormConfiguration.from_dict(
                reply.json().get('config'))
            LOG.info("New configuration was loaded from server: %r" %
                     (WormConfiguration.as_dict(), ))
        except Exception as exc:
            # we don't continue with default conf here because it might be dangerous
            LOG.error(
                "Error parsing JSON reply from control server %s (%s): %s",
                WormConfiguration.current_server, reply._content, exc)
            raise Exception(
                "Couldn't load from from server's configuration, aborting. %s"
                % exc)

        if unknown_variables:
            ControlClient.send_config_error()
示例#3
0
    def wakeup(parent=None, has_internet_access=None):
        if parent:
            LOG.debug("parent: %s" % (parent,))

        hostname = gethostname()
        if not parent:
            parent = GUID

        if has_internet_access is None:
            has_internet_access = check_internet_access(WormConfiguration.internet_services)

        monkey = {'guid': GUID,
                  'hostname': hostname,
                  'ip_addresses': local_ips(),
                  'description': " ".join(platform.uname()),
                  'internet_access': has_internet_access,
                  'config': WormConfiguration.as_dict(),
                  'parent': parent}

        if ControlClient.proxies:
            monkey['tunnel'] = ControlClient.proxies.get('https')

        requests.post("https://%s/api/monkey" % (WormConfiguration.current_server,),
                      data=json.dumps(monkey),
                      headers={'content-type': 'application/json'},
                      verify=False,
                      proxies=ControlClient.proxies,
                      timeout=20)
示例#4
0
    def wakeup(parent=None, has_internet_access=None):
        if parent:
            LOG.debug("parent: %s" % (parent, ))

        hostname = gethostname()
        if not parent:
            parent = GUID

        if has_internet_access is None:
            has_internet_access = check_internet_access(
                WormConfiguration.internet_services)

        monkey = {
            'guid': GUID,
            'hostname': hostname,
            'ip_addresses': local_ips(),
            'description': " ".join(platform.uname()),
            'internet_access': has_internet_access,
            'config': WormConfiguration.as_dict(),
            'parent': parent
        }

        if ControlClient.proxies:
            monkey['tunnel'] = ControlClient.proxies.get('https')

        requests.post("https://%s/api/monkey" %
                      (WormConfiguration.current_server, ),
                      data=json.dumps(monkey),
                      headers={'content-type': 'application/json'},
                      verify=False,
                      proxies=ControlClient.proxies,
                      timeout=20)
示例#5
0
    def initialize(self):
        # get local ip addresses
        self._ip_addresses = local_ips()

        if not self._ip_addresses:
            raise Exception("Cannot find local IP address for the machine")

        LOG.info("Found local IP addresses of the machine: %r", self._ip_addresses)
        # for fixed range, only scan once.
        if WormConfiguration.range_class is FixedRange:
            self._ranges = [WormConfiguration.range_class(None)]
        else:
            self._ranges = [WormConfiguration.range_class(ip_address)
                            for ip_address in self._ip_addresses]
        if WormConfiguration.local_network_scan:
            self._ranges += [FixedRange([ip_address for ip_address in get_ips_from_interfaces()])]
        LOG.info("Base local networks to scan are: %r", self._ranges)
示例#6
0
    def wakeup(parent=None, default_tunnel=None, has_internet_access=None):
        LOG.debug("Trying to wake up with C&C servers list: %r" % WormConfiguration.command_servers)
        if parent or default_tunnel:
            LOG.debug("parent: %s, default_tunnel: %s" % (parent, default_tunnel))
        hostname = gethostname()
        if not parent:
            parent = GUID

        if has_internet_access is None:
            has_internet_access = check_internet_access(WormConfiguration.internet_services)

        for server in WormConfiguration.command_servers:
            try:
                WormConfiguration.current_server = server

                monkey = {'guid': GUID,
                          'hostname': hostname,
                          'ip_addresses': local_ips(),
                          'description': " ".join(platform.uname()),
                          'internet_access': has_internet_access,
                          'config': WormConfiguration.as_dict(),
                          'parent': parent}

                if ControlClient.proxies:
                    monkey['tunnel'] = ControlClient.proxies.get('https')

                debug_message = "Trying to connect to server: %s" % server
                if ControlClient.proxies:
                    debug_message += " through proxies: %s" % ControlClient.proxies
                LOG.debug(debug_message)
                reply = requests.post("https://%s/api/monkey" % (server,),
                                      data=json.dumps(monkey),
                                      headers={'content-type': 'application/json'},
                                      verify=False,
                                      proxies=ControlClient.proxies,
                                      timeout=20)
                break

            except Exception as exc:
                WormConfiguration.current_server = ""
                LOG.warn("Error connecting to control server %s: %s", server, exc)

        if not WormConfiguration.current_server:
            if not ControlClient.proxies:
                LOG.info("Starting tunnel lookup...")
                proxy_find = tunnel.find_tunnel(default=default_tunnel)
                if proxy_find:
                    proxy_address, proxy_port = proxy_find
                    LOG.info("Found tunnel at %s:%s" % (proxy_address, proxy_port))
                    ControlClient.proxies['https'] = 'https://%s:%s' % (proxy_address, proxy_port)
                    ControlClient.wakeup(parent=parent, has_internet_access=has_internet_access)
                else:
                    LOG.info("No tunnel found")
示例#7
0
    def load_control_config():
        if not WormConfiguration.current_server:
            return
        try:
            reply = requests.get("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID),
                                 verify=False,
                                 proxies=ControlClient.proxies)

        except Exception as exc:
            LOG.warn("Error connecting to control server %s: %s",
                     WormConfiguration.current_server, exc)
            return

        try:
            unknown_variables = WormConfiguration.from_dict(reply.json().get('config'))
            LOG.info("New configuration was loaded from server: %r" % (WormConfiguration.as_dict(),))
        except Exception as exc:
            # we don't continue with default conf here because it might be dangerous
            LOG.error("Error parsing JSON reply from control server %s (%s): %s",
                      WormConfiguration.current_server, reply._content, exc)
            raise Exception("Couldn't load from from server's configuration, aborting. %s" % exc)

        if unknown_variables:
            ControlClient.send_config_error()
示例#8
0
    def wakeup(parent=None, default_tunnel=None, has_internet_access=None):
        LOG.debug("Trying to wake up with C&C servers list: %r" %
                  WormConfiguration.command_servers)
        if parent or default_tunnel:
            LOG.debug("parent: %s, default_tunnel: %s" %
                      (parent, default_tunnel))
        hostname = gethostname()
        if not parent:
            parent = GUID

        if has_internet_access is None:
            has_internet_access = check_internet_access(
                WormConfiguration.internet_services)

        for server in WormConfiguration.command_servers:
            try:
                WormConfiguration.current_server = server

                monkey = {
                    'guid': GUID,
                    'hostname': hostname,
                    'ip_addresses': local_ips(),
                    'description': " ".join(platform.uname()),
                    'internet_access': has_internet_access,
                    'config': WormConfiguration.as_dict(),
                    'parent': parent
                }

                if ControlClient.proxies:
                    monkey['tunnel'] = ControlClient.proxies.get('https')

                debug_message = "Trying to connect to server: %s" % server
                if ControlClient.proxies:
                    debug_message += " through proxies: %s" % ControlClient.proxies
                LOG.debug(debug_message)
                reply = requests.post(
                    "https://%s/api/monkey" % (server, ),
                    data=json.dumps(monkey),
                    headers={'content-type': 'application/json'},
                    verify=False,
                    proxies=ControlClient.proxies,
                    timeout=20)
                break

            except Exception, exc:
                WormConfiguration.current_server = ""
                LOG.warn("Error connecting to control server %s: %s", server,
                         exc)
示例#9
0
    def wakeup(parent=None, default_tunnel=None):
        LOG.debug("Trying to wake up with C&C servers list: %r" % WormConfiguration.command_servers)
        if parent or default_tunnel:
            LOG.debug("parent: %s, default_tunnel: %s" % (parent, default_tunnel))
        hostname = gethostname()
        if not parent:
            parent = GUID

        for server in WormConfiguration.command_servers:
            try:
                WormConfiguration.current_server = server

                monkey = {'guid': GUID,
                          'hostname': hostname,
                          'ip_addresses': local_ips(),
                          'description': " ".join(platform.uname()),
                          'internet_access': check_internet_access(WormConfiguration.internet_services),
                          'config': WormConfiguration.as_dict(),
                          'parent': parent}

                if ControlClient.proxies:
                    monkey['tunnel'] = ControlClient.proxies.get('https')

                debug_message = "Trying to connect to server: %s" % server
                if ControlClient.proxies:
                    debug_message += " through proxies: %s" % ControlClient.proxies
                LOG.debug(debug_message)
                reply = requests.post("https://%s/api/monkey" % (server,),
                                      data=json.dumps(monkey),
                                      headers={'content-type': 'application/json'},
                                      verify=False,
                                      proxies=ControlClient.proxies,
                                      timeout=20)
                break

            except Exception, exc:
                WormConfiguration.current_server = ""
                LOG.warn("Error connecting to control server %s: %s", server, exc)
示例#10
0
    @staticmethod
    def load_control_config():
        if not WormConfiguration.current_server:
            return        
        try:
            reply = requests.get("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID),
                                 verify=False,
                                 proxies=ControlClient.proxies)

        except Exception, exc:
            LOG.warn("Error connecting to control server %s: %s",
                     WormConfiguration.current_server, exc)
            return

        try:
            WormConfiguration.from_dict(reply.json().get('config'))
            LOG.info("New configuration was loaded from server: %r" % (WormConfiguration.as_dict(),))
        except Exception, exc:
            # we don't continue with default conf here because it might be dangerous
            LOG.error("Error parsing JSON reply from control server %s (%s): %s",
                      WormConfiguration.current_server, reply._content, exc)
            raise Exception("Couldn't load from from server's configuration, aborting. %s" % exc)

    @staticmethod
    def check_for_stop():
        ControlClient.load_control_config()
        return not WormConfiguration.alive

    @staticmethod
    def download_monkey_exe(host):
        if not WormConfiguration.current_server:
示例#11
0
def main():
    global LOG

    if 2 > len(sys.argv):
        return True

    monkey_mode = sys.argv[1]

    if not (monkey_mode in [MONKEY_ARG, DROPPER_ARG]):
        return True

    config_file = EXTERNAL_CONFIG_FILE

    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('-c', '--config')
    opts, monkey_args = arg_parser.parse_known_args(sys.argv[2:])
    if opts.config:
        config_file = opts.config
    if os.path.isfile(config_file):
        # using print because config can also change log locations
        print("Loading config from %s." % config_file)
        try:
            with open(config_file) as config_fo:
                json_dict = json.load(config_fo)
                WormConfiguration.from_dict(json_dict)
        except ValueError as e:
            print("Error loading config: %s, using default" % (e,))
    else:
        print("Config file wasn't supplied and default path: %s wasn't found, using internal default" % (config_file,))

    print("Loaded Configuration: %r" % WormConfiguration.as_dict())

    # Make sure we're not in a machine that has the kill file
    kill_path = os.path.expandvars(WormConfiguration.kill_file_path_windows) if sys.platform == "win32" else WormConfiguration.kill_file_path_linux
    if os.path.exists(kill_path):
        print("Kill path found, finished run")
        return True

    try:
        if MONKEY_ARG == monkey_mode:
            log_path = os.path.expandvars(
                WormConfiguration.monkey_log_path_windows) if sys.platform == "win32" else WormConfiguration.monkey_log_path_linux
            monkey_cls = ChaosMonkey
        elif DROPPER_ARG == monkey_mode:
            log_path = os.path.expandvars(
                WormConfiguration.dropper_log_path_windows) if sys.platform == "win32" else WormConfiguration.dropper_log_path_linux
            monkey_cls = MonkeyDrops
        else:
            return True
    except ValueError:
        return True

    if WormConfiguration.use_file_logging:
        LOG_CONFIG['handlers']['file']['filename'] = log_path
        LOG_CONFIG['root']['handlers'].append('file')
    else:
        del LOG_CONFIG['handlers']['file']

    logging.config.dictConfig(LOG_CONFIG)
    LOG = logging.getLogger()

    def log_uncaught_exceptions(ex_cls, ex, tb):
        LOG.critical(''.join(traceback.format_tb(tb)))
        LOG.critical('{0}: {1}'.format(ex_cls, ex))

    sys.excepthook = log_uncaught_exceptions

    LOG.info(">>>>>>>>>> Initializing monkey (%s): PID %s <<<<<<<<<<",
             monkey_cls.__name__, os.getpid())

    monkey = monkey_cls(monkey_args)
    monkey.initialize()

    try:
        monkey.start()

        if WormConfiguration.serialize_config:
            with open(config_file, 'w') as config_fo:
                json_dict = WormConfiguration.as_dict()
                json.dump(json_dict, config_fo, skipkeys=True, sort_keys=True, indent=4, separators=(',', ': '))

        return True
    finally:
        monkey.cleanup()
示例#12
0
    def load_control_config():
        if not WormConfiguration.current_server:
            return
        try:
            reply = requests.get("https://%s/api/monkey/%s" %
                                 (WormConfiguration.current_server, GUID),
                                 verify=False,
                                 proxies=ControlClient.proxies)

        except Exception, exc:
            LOG.warn("Error connecting to control server %s: %s",
                     WormConfiguration.current_server, exc)
            return

        try:
            WormConfiguration.from_dict(reply.json().get('config'))
            LOG.info("New configuration was loaded from server: %r" %
                     (WormConfiguration.as_dict(), ))
        except Exception, exc:
            # we don't continue with default conf here because it might be dangerous
            LOG.error(
                "Error parsing JSON reply from control server %s (%s): %s",
                WormConfiguration.current_server, reply._content, exc)
            raise Exception(
                "Couldn't load from from server's configuration, aborting. %s"
                % exc)

    @staticmethod
    def check_for_stop():
        ControlClient.load_control_config()
        return not WormConfiguration.alive
示例#13
0
    def load_control_config():
        if not WormConfiguration.current_server:
            return
        try:
            reply = requests.get("https://%s/api/monkey/%s" %
                                 (WormConfiguration.current_server, GUID),
                                 verify=False,
                                 proxies=ControlClient.proxies)

        except Exception, exc:
            LOG.warn("Error connecting to control server %s: %s",
                     WormConfiguration.current_server, exc)
            return

        try:
            unknown_variables = WormConfiguration.from_dict(
                reply.json().get('config'))
            LOG.info("New configuration was loaded from server: %r" %
                     (WormConfiguration.as_dict(), ))
        except Exception, exc:
            # we don't continue with default conf here because it might be dangerous
            LOG.error(
                "Error parsing JSON reply from control server %s (%s): %s",
                WormConfiguration.current_server, reply._content, exc)
            raise Exception(
                "Couldn't load from from server's configuration, aborting. %s"
                % exc)

        if unknown_variables:
            ControlClient.send_config_error()

    @staticmethod